package com.hmall.service;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hdmall.business.common.common.Const;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.util.*;
import com.hmall.controller.JpushController;
import com.hmall.mapper.*;
import com.hmall.model.*;
import com.hmall.util.*;
import com.hmall.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * @Author zhoutao
 * @Date 2018/11/8 13:07
 * @Param
 * @return
 * @Description //
 */
@Slf4j
@Service
public class DealerService {

    private  SysUserRoleMapper sysUserRoleMapper;

    private  SysUserMapper userMapper;

    private  MallDealerMapper mallDealerMapper;

    private  SysMenuMapper menuMapper;

    private  SysUserExtraMapper sysUserExtraMapper;

    private  SysCustomerMapper customerMapper;

    private  SysUserDeptMapper sysUserDeptMapper;

    private  MallOrderMapper mallOrderMapper;

    private  MallOrderItemMapper mallOrderItemMapper;

    private  SysDeptCustomerMapper sysDeptCustomerMapper;

    private  MallPaymentUnpayMapper mallPaymentUnpayMapper;

    private  MallPaymentVoucherMapper mallPaymentVoucherMapper;

    private  MallPriceMapper mallPriceMapper;

    private  SysDeptMapper sysDeptMapper;

    private  MallAttrConnectMapper mallAttrConnectMapper;

    private  MallShopMapper mallShopMapper;

    private  MallProductMapper mallProductMapper;

    private  MallShippingMapper mallShippingMapper;

    private  MallDistmodeMapper mallDistmodeMapper;

    private  MallProductPlanMapper mallProductPlanMapper;

    private  MallProductPlanItemMapper mallProductPlanItemMapper;

    private  MallOrderFufillmentMapper mallOrderFufillmentMapper;

    private  MallOrderFufillmentParentMapper mallOrderFufillmentParentMapper;

    private  SysCustomerCreditMapper sysCustomerCreditMapper;

    private  UserService userService;

    private  CommentService commentService;

    private  SysCustomerStatementMapper sysCustomerStatementMapper;

    private  JpushController jpushController;

    private  MallProductStockMapper mallProductStockMapper;

    private  MallOrderRemarkMapper mallOrderRemarkMapper;

    private  MallProductForwardStockMapper mallProductForwardStockMapper;

    private  MallOrderItemDetailMapper mallOrderItemDetailMapper;

    private  MallTransportMapper mallTransportMapper;

    private  JedisPool jedisPool;

    @Lazy
    private  MerchandiserService merchandiserService;

    private final Integer HAVE_PAY = 20;

    private final Integer HAVE_SEND = 60;

    private final Integer HAVE_FINISH = 50;

    private  SysCustomerUserIsStarMapper sysCustomerUserIsStarMapper;

    private  DictionMapper dictionMapper;

    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @Autowired
    public DealerService(SysUserMapper userMapper, SysUserRoleMapper sysUserRoleMapper, MallOrderFufillmentParentMapper mallOrderFufillmentParentMapper, MallTransportMapper mallTransportMapper, MallDealerMapper mallDealerMapper, SysMenuMapper menuMapper, MallOrderItemDetailMapper mallOrderItemDetailMapper, SysUserExtraMapper sysUserExtraMapper, MallPaymentVoucherMapper mallPaymentVoucherMapper, JedisPool jedisPool, UserService userService, MerchandiserService merchandiserService, SysDeptMapper sysDeptMapper, MallShopMapper mallShopMapper, MallPaymentUnpayMapper mallPaymentUnpayMapper, JpushController jpushController, SysCustomerMapper customerMapper, MallProductMapper mallProductMapper, SysCustomerUserIsStarMapper sysCustomerUserIsStarMapper, SysUserDeptMapper sysUserDeptMapper, MallShippingMapper mallShippingMapper, MallOrderFufillmentMapper mallOrderFufillmentMapper, MallOrderMapper mallOrderMapper, SysCustomerStatementMapper sysCustomerStatementMapper, MallOrderRemarkMapper mallOrderRemarkMapper, MallProductPlanItemMapper mallProductPlanItemMapper, SysCustomerCreditMapper sysCustomerCreditMapper, MallAttrConnectMapper mallAttrConnectMapper, MallProductPlanMapper mallProductPlanMapper, MallPriceMapper mallPriceMapper, MallOrderItemMapper mallOrderItemMapper, SysDeptCustomerMapper sysDeptCustomerMapper, MallDistmodeMapper mallDistmodeMapper, CommentService commentService, MallProductForwardStockMapper mallProductForwardStockMapper, MallProductStockMapper mallProductStockMapper, DictionMapper dictionMapper) {
        this.userMapper = userMapper;
        this.sysUserRoleMapper = sysUserRoleMapper;
        this.mallOrderFufillmentParentMapper = mallOrderFufillmentParentMapper;
        this.mallTransportMapper = mallTransportMapper;
        this.mallDealerMapper = mallDealerMapper;
        this.menuMapper = menuMapper;
        this.mallOrderItemDetailMapper = mallOrderItemDetailMapper;
        this.sysUserExtraMapper = sysUserExtraMapper;
        this.mallPaymentVoucherMapper = mallPaymentVoucherMapper;
        this.jedisPool = jedisPool;
        this.userService = userService;
        this.merchandiserService = merchandiserService;
        this.sysDeptMapper = sysDeptMapper;
        this.mallShopMapper = mallShopMapper;
        this.mallPaymentUnpayMapper = mallPaymentUnpayMapper;
        this.jpushController = jpushController;
        this.customerMapper = customerMapper;
        this.mallProductMapper = mallProductMapper;
        this.sysCustomerUserIsStarMapper = sysCustomerUserIsStarMapper;
        this.sysUserDeptMapper = sysUserDeptMapper;
        this.mallShippingMapper = mallShippingMapper;
        this.mallOrderFufillmentMapper = mallOrderFufillmentMapper;
        this.mallOrderMapper = mallOrderMapper;
        this.sysCustomerStatementMapper = sysCustomerStatementMapper;
        this.mallOrderRemarkMapper = mallOrderRemarkMapper;
        this.mallProductPlanItemMapper = mallProductPlanItemMapper;
        this.sysCustomerCreditMapper = sysCustomerCreditMapper;
        this.mallAttrConnectMapper = mallAttrConnectMapper;
        this.mallProductPlanMapper = mallProductPlanMapper;
        this.mallPriceMapper = mallPriceMapper;
        this.mallOrderItemMapper = mallOrderItemMapper;
        this.sysDeptCustomerMapper = sysDeptCustomerMapper;
        this.mallDistmodeMapper = mallDistmodeMapper;
        this.commentService = commentService;
        this.mallProductForwardStockMapper = mallProductForwardStockMapper;
        this.mallProductStockMapper = mallProductStockMapper;
        this.dictionMapper = dictionMapper;
    }

    /**
     * @Date 2018/11/8 13:06
     * @Param [userId]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.DealerUserVo>>
     * @Description // 看到的都是这个办事处下的人员列表
     */
    public ServerResponse<List<DealerUserVo>> getSalesManInformation(Integer userId) {

        SysUser user = userMapper.selectByPrimaryKey(userId);
        if (user.getDeptId() == null) {
            return ServerResponse.createByErrorMessage("该用户是普通用户，无法获取信息");
        }

        List<SysUser> userList = userMapper.listDeptUserByDeptId(user.getDeptId());

        List<DealerUserVo> dealerUserVoList = new ArrayList<>();
        for (SysUser subUser : userList) {
            DealerUserVo dealerUserVo = new DealerUserVo();
            dealerUserVo.setRealName(subUser.getRealName());
            dealerUserVo.setUserName(subUser.getUsername());
            dealerUserVo.setTelphone(subUser.getPhone());
            dealerUserVo.setAvator(subUser.getAvatar());
            MallDealer mallDealer = mallDealerMapper.selectAllByDeptId(subUser.getDeptId());
            dealerUserVo.setDealerName(mallDealer.getDealerName());
            dealerUserVoList.add(dealerUserVo);
        }

        return ServerResponse.createBySuccess(dealerUserVoList);

    }

    public ServerResponse<Map<String, String>> backLogin(String agentUserName, String password) {

        String []str = AgentUtil.deleteAgentUserName(agentUserName).getData().split(":");
        String agent = str[0];
        String username = str[1];


        if (agent == null) {
            return ServerResponse.createByStatus(19, "未知设备,无法登陆");
        }


        int count = userMapper.checkUsername(username);
        if (count <= 0) {
            return ServerResponse.createByStatus(11, "用户名不存在");
        }

        //在部门人员列表中找人
        SysUser deptUser = userMapper.selectDeptUserByUserName(username);
        if (deptUser != null && deptUser.getDeptId() != null && ENCODER.matches(password, deptUser.getPassword())) {
            return loginSubMethod(deptUser, agent);
        } else {
            return ServerResponse.createByErrorMessage("密码错误");
        }
    }

    /**
     * @Date 2018/11/8 13:07
     * @Param [user, agent]
     * @return com.hmall.common.ServerResponse<java.util.Map<java.lang.String,java.lang.String>>
     * @Description //   账号密码验证结束之后，进行登录 加-back后缀防止与nomal冲突
     */
    private ServerResponse<Map<String, String>> loginSubMethod(SysUser user, String agent) {

        Jedis jedis = jedisPool.getResource();
        String agentUserName = agent + user.getUsername() + "-back";

        String userToken = DataFomateUtil.sysUserToString(user);

        jedis.setex(agentUserName + "REDIS_USER", 24 * 1000 * 3600, userToken);

        // 检查是否已经登陆，如果已经登陆，就不用创建新Token并设置过期时间，如果是过期了，
        //为了测试设为30天  安卓和IOS需要登录永远有效
        String accessToken = jedis.get(agentUserName);
        //如果token在redis中没设置，设置到redis中
        if (accessToken == null) {
            accessToken = TokenUtil.createJwtToken(agentUserName);
            // Token超时间隔设为24小时
            //setex 以秒为单位
            int second = 24 * 3600 * 365 * 10;
            jedis.setex(agentUserName, second, accessToken);

        }
        //如果token已经有了取出来
        Map<String, String> tokenMap = new HashMap<>(16);
        tokenMap.put("nickName", user.getQuestion());
        tokenMap.put("avator", user.getAvatar());
        tokenMap.put("token", accessToken);
        tokenMap.put("userName", user.getUsername());
        tokenMap.put("userId", user.getUserId().toString());
        tokenMap.put("exchange", "back_message_exchg");
        tokenMap.put("deptId",user.getDeptId().toString());

        // 2018/10/13
        // 0表示不是跟单员 1表示是
        Integer type = 0;
        if(Const.MERCH_DEPT_ID.equals(user.getDeptId())){
            type = 1;
        }else if(checkFinance(user.getUserId())){
            type = 2;
        }

        tokenMap.put("roleType", type.toString());

        int userId = user.getUserId();

//        登录成功后，如果没有alias插入，有的话更新

        if(agent.contains("PC")) {
            return ServerResponse.createBySuccess(tokenMap);
        }
        //如果是PC端不操作
        int countUser = sysUserExtraMapper.selectByUserId(userId);

        String alias = agent.substring(0, agent.length()- 1) + "_" + user.getUsername();
        //办事处人登录 其实可以做一个方法
        if(countUser == 0){
            SysUserExtra sysUserExtra = new SysUserExtra();
            sysUserExtra.setUserId(userId);
            sysUserExtra.setAlias(alias);
            sysUserExtraMapper.insert(sysUserExtra);
        }else {
            sysUserExtraMapper.updateAlias(userId, alias);
        }
        jedis.set("Alias-" + user.getUsername(), alias);
        jedis.close();
        return ServerResponse.createBySuccess(tokenMap);
    }


    /**
     * @Date 2018/11/8 13:16
     * @Param [userId, pageNum, pageSize]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo>
     * @Description //
     *  //规则：
     *     //1.业务员只能看见自己负责的客户下的用户
     *     //2.办事处管理员能看见所有客户下的用户
     *     //3.办事处和客户绑定
     *     //4.根据菜单项来决定是什么权限
     *     //5.0表示业务员 1表示管理员 2表示无该权限看，在后台要设置菜单项
     */
    public ServerResponse<PageVo<CustomerNomalUserVo>> listCustomerUser(Integer userId, Integer pageNum, Integer pageSize) {


        //2018/11/9 要加入第一条消息以及未读消息数目
        List<CustomerNomalUserVo> customerNomalUserVoList = new ArrayList<>();
        List<String> menuList = menuMapper.listMenuByUserId(userId);
        int role = DealerMenuUtil.getBackRole(menuList);
        if (role == 0) {

            customerNomalUserVoList = getCustomerUserListByOneBackUser(userId);

        } else if(role == 1){
            //客户全列表
            //1.根据办事员的user找到他所在的办事处
            Integer deptId = userMapper.selectByPrimaryKey(userId).getDeptId();

            //2.先找出所有的业务员（包括自己的列表）
            List<Integer> salesmanIdList = userMapper.selectUserIdListByDeptId(deptId);
            for (Integer salesmanId : salesmanIdList) {
                customerNomalUserVoList.addAll(getCustomerUserListByOneBackUser(salesmanId));
            }
        }else{
            return ServerResponse.createByErrorMessage("无权限");
        }

//        //遍历一遍消息把每个用户最新的一条放进去
//        Jedis jedis = jedisPool.getResource();
//
//        //500客户
//        Map<String, String> map = new HashMap<>(500);
//        //自己是接收方
//        String messageKey = "IM-back-" + backUsername;
//        Set<String> set = jedis.zrevrange(messageKey, 0, -1);
//
//        //设置最近的一条消息
//        for(String id : set){
//            //如果最近信息数目已经够了就不再需要查找
//            if(map.size() == customerNomalUserVoList.size()) {
//                break;
//            }
//            if (System.currentTimeMillis() >= jedis.zscore(messageKey, id).longValue()) {
//                jedis.zrem(messageKey, id);
//            }
//            MessageJsonVo messageJsonVo = JsonUtils.jsonStrToObject(id, MessageJsonVo.class);
//            String sendUsername = messageJsonVo.getSendModel().getUsername();
//            String receiveUsername = messageJsonVo.getReceiveModel().getUsername();
//            String customerUsername;
//            if(backUsername.equals(sendUsername)){
//                customerUsername = receiveUsername;
//            }else{
//                customerUsername = sendUsername;
//            }
//           if(null != customerUsername && !map.containsKey(customerUsername)){
//               map.put(customerUsername, id);
//           }
//        }

//        for(CustomerNomalUserVo customerNomalUserVo : customerNomalUserVoList){
//            String key = "noReadCount" + "-" + backUsername+ "-" + customerNomalUserVo.getCustomerUserName() ;
//            Integer noReadCount = 0;
//            if(jedis.exists(key)) {
//                noReadCount = Integer.valueOf(jedis.get(key));
//            }
//            customerNomalUserVo.setNoReadCount(noReadCount);
//            String customerUsername = customerNomalUserVo.getCustomerRegisterUserName();
//            String latestMessage = "";
//            if(null != map.get(customerUsername)){
//                latestMessage = map.get(customerUsername).toString();
//            }
//            customerNomalUserVo.setLatestMessage(latestMessage);
//        }
//        jedis.close();

        int total = customerNomalUserVoList.size();
        int pageStart = (pageNum - 1) * pageSize;
        int pageEnd = Math.min(total, pageStart + pageSize);
        List<CustomerNomalUserVo> subCustomerNomalUserVoList = customerNomalUserVoList.subList(pageStart, pageEnd);
        PageVo<CustomerNomalUserVo> pageVo = new PageVo<>(pageNum, pageSize, total, subCustomerNomalUserVoList);
        return ServerResponse.createBySuccess(pageVo);
    }

    /**
     * @Date 2018/11/8 13:16
     * @Param [salesmanId]
     * @return java.util.List<com.hmall.vo.CustomerNomalUserVo>
     * @Description // //根据公司得到一个公司下的所有用户的数据
     */
    private List<CustomerNomalUserVo> getCustomerUserListByOneBackUser(Integer salesmanId) {
        //不确定，用username代替
        String salesmanName = userMapper.selectByPrimaryKey(salesmanId).getRealName();

        //一个客户（公司）只绑定一个办事处的一个业务员
        //一个客户可以有多个用户
        List<Integer> customerIdList = customerMapper.selectCustomerIdLisstBySalsemanId(salesmanId);

        List<CustomerNomalUserVo> customerNomalUserVoList = new ArrayList<>();
        for (Integer customerId : customerIdList) {

            //找到该客户的所有用户
            List<Integer> userIdList = getCustomerUserIdList(customerId);
            Set<String> usernameSet = new HashSet<>();
            for (Integer userId : userIdList) {


                CustomerNomalUserVo customerNomalUserVo = new CustomerNomalUserVo();
                customerNomalUserVo.setSalesmanName(salesmanName);
                customerNomalUserVo.setCustomerId(customerId);
                SysCustomer customer = customerMapper.selectByPrimaryKey(customerId);
                String customerName = customer.getBusName();
                String address = customer.getBusAddress();
                SysCustomerUserIsStar sysCustomerUserIsStar = sysCustomerUserIsStarMapper.selectIsStar(salesmanId, customerId);
                Boolean isStar = sysCustomerUserIsStar != null && (sysCustomerUserIsStar.getIsStar() == 1);

                //起始，结束时间

                BigDecimal totalTurnover = new BigDecimal(0);
                List<SysCustomerStatement> sysCustomerStatementList = sysCustomerStatementMapper.selectByCustomerId(customerId);
                for(SysCustomerStatement customerStatement : sysCustomerStatementList){
                    totalTurnover = totalTurnover.add(customerStatement.getThisMonthFufillmentPayment());
                }

                customerNomalUserVo.setAddress(address);
                customerNomalUserVo.setIsStar(isStar);
                customerNomalUserVo.setCustomerName(customerName);
                customerNomalUserVo.setTotalTurnover(totalTurnover);
                customerNomalUserVo.setCustomerUserId(userId);
                SysUser user = userMapper.selectByPrimaryKey(userId);
                //数据不准
                if (user == null) {
                    continue;
                }
                customerNomalUserVo.setCustomerRegisterUserName(user.getUsername());
                customerNomalUserVo.setCustomerUserName(user.getRealName());
                customerNomalUserVo.setCustomerUserNickName(user.getQuestion());


                CustomerInformationVo customerInformationVo = getCustomerInformation(userId).getData();
                customerNomalUserVo.setExceedUnPayment(customerInformationVo.getExceedUnPayment());
                customerNomalUserVo.setAccountPeriod(customerInformationVo.getAccountPeriod());
                customerNomalUserVo.setCustomerType(customerInformationVo.getCustomerType());

                customerNomalUserVoList.add(customerNomalUserVo);
            }
        }
        return customerNomalUserVoList;
    }

    /**
     * @Date 2018/11/8 13:17
     * @Param [customerId, startDate, endDate]
     * @return java.math.BigDecimal
     * @Description // //根据公司的id得到该公司的交易总额（支持时间）
     */
    @Deprecated
    private BigDecimal getTotalTurnover(Integer customerId, Date startDate, Date endDate) {

        //成交总额
        //公司的成交总额 从mall_payment_voucher中取fact_payment
        //逻辑有问题，以后做定时任务
        //1.先根据公司找到该公司下的所有用户
        //2.找到order表的payment状态为20或40或50

        //9.27改为 20 60 50

        List<Integer> userIdList = sysUserDeptMapper.selectUserIdListByCustomerId(customerId);


        BigDecimal totalTurnover = new BigDecimal(0.0);
        if (userIdList.size() != 0) {
            //交易金额
            totalTurnover = mallOrderMapper.getPaymentByUserIdList(userIdList, HAVE_PAY, HAVE_SEND, HAVE_FINISH, startDate, endDate);
        }
        return totalTurnover == null ? new BigDecimal(0) : totalTurnover;

    }

    
   /**
    * @Date 2018/11/8 14:22
    * @Param [salesmanId, customerUserId] 
    * @return com.hmall.common.ServerResponse<com.hmall.vo.CustomerDetialVo>
    * @Description // 一个公司下可能有多个账号        
    */
    public ServerResponse<CustomerDetialVo> customerDetail(Integer salesmanId, Integer customerUserId) {

        CustomerDetialVo customerDetialVo = new CustomerDetialVo();

        SysUser user = userMapper.selectByPrimaryKey(customerUserId);

        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(customerUserId);
        if (customerId == null) {
            return ServerResponse.createByErrorMessage("该用户暂未绑定公司");
        }
        //————————————————————————
        //先设置基础信息

        CustomerBaseInformation customerBaseInformation = getBaseCustomerInformation(customerId, user);
        customerDetialVo.setCustomerBaseInformation(customerBaseInformation);
        log.info("公司基础信息设置成功");
        //————————————————————————
        //设置用户基础信息
        CustomerUserInformation customerUserInformation = getCustomerUserInformation(customerId, user, salesmanId);
        customerDetialVo.setCustomerUserInformation(customerUserInformation);
        log.info("设置用户基础信息成功");
        //——————————————————————
        //交易信息trade
        CustomerTradeInformation customerTradeInformation = getCustomerTradeInformation(customerId);
        customerDetialVo.setCustomerTradeInformation(customerTradeInformation);
        log.info("设置公司交易信息成功");
        //—————————————————————————
        //历史跟进
        //写死 没法弄
        Long orderNo = 13232323232L;
        String complaintMessage = "产品质量不好";
        Date complaintTime = new Date();
        String replyMessage = "马上处理";
        Date replyTime = new Date();
        String followRemark = "处理完成";
        Date followTime = new Date();
        String img = "http://47.98.213.218:3333/api/resouces/201852210266a7223480677d54cb08f16dc5c691a99b.jpg";

        CustomerHistoryFollow customerHistoryFollow = new CustomerHistoryFollow(orderNo, complaintMessage, complaintTime, replyMessage, replyTime, followRemark, followTime, img);
        customerDetialVo.setCustomerHistoryFollow(customerHistoryFollow);
        log.info("设置历史跟进成功");
        //————————————————————————

        return ServerResponse.createBySuccess(customerDetialVo);
    }

    /**
     * @Date 2018/11/8 15:15
     * @Param [customerUserId]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.CustomerBaseInformation>
     * @Description // 得到公司的基础信息
     */
    private CustomerBaseInformation getBaseCustomerInformation(Integer customerId, SysUser user){

        String customerName = customerMapper.selectByPrimaryKey(customerId).getBusName();
        //上月成交金额
        //1.根据用户得到客户信息
        //2.根据客户信息得到客户下的所有用户
        //3.去订单表查询上个月订单总额

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        //当前年份
        int year = calendar.get(Calendar.YEAR);

        //当前月份
        int month = calendar.get(Calendar.MONTH);

        calendar.set(year, month - 1, 1);
        calendar.set(year, month, 1);

        //一个客户默认一个业务员
        //一个客户可以有多个用户
        BigDecimal lastMonthPayment = new BigDecimal(0.0);

        //2018/9/27 已经有了statement表
        SysCustomerStatement sysCustomerStatement = sysCustomerStatementMapper.selectAccount(customerId, year, month);
        if(null != sysCustomerStatement) {
            lastMonthPayment = sysCustomerStatement.getLastMonthUnpayment();
        }
        //getTotalTurnover(customerId, startDate, endDate);

        //客户欠款总额
        //1.找到该客户下的所有的用户
        //2.找到用户的所有订单
        //3.找到客户订单的欠款金额

        //直接从unPayment中取 2018/9/27 改
        BigDecimal totalArrears = new BigDecimal(0.0);
        MallPaymentUnpay mallPaymentUnpay = mallPaymentUnpayMapper.getTotalArrearsByCustomerId(customerId);
//        MallPaymentUnpay
        if (mallPaymentUnpay != null) {
            totalArrears = mallPaymentUnpay.getUnpayPayment();
        }
        BigDecimal totalPayment = new BigDecimal(0.0);

        List<SysCustomerStatement> sysCustomerStatementList = sysCustomerStatementMapper.selectByCustomerId(customerId);
        for(SysCustomerStatement customerStatement : sysCustomerStatementList){
            totalPayment = totalPayment.add(customerStatement.getThisMonthFufillmentPayment());
        }
        return new CustomerBaseInformation(user.getRealName(), customerName, user.getPhone(), lastMonthPayment, totalArrears, totalPayment);
    }

    /**
     * @Date 2018/11/8 15:26
     * @Param [customerId, user, salesmanId]
     * @return com.hmall.vo.CustomerUserInformation
     * @Description // 得到用户基础信息
     */
    private CustomerUserInformation getCustomerUserInformation(Integer customerId, SysUser user, Integer salesmanId){
        //设置用户基本信息
        Date registerTime = sysDeptMapper.selectCreateTimeByCustomerId(customerId).getCreateTime();
        String username = user.getRealName();
        //所在城市？暂用所在地址
        SysCustomer sysCustomer = customerMapper.selectByPrimaryKey(customerId);
        String customerCity = sysCustomer.getBusAddress();
        //常用产品规则
        // 该公司最近结算的三个订单里面产品数目最多的一个
        //1.找到最近的三个orderNo,状态为
        //2.根据oderNo找orderItem下最多的type数目
        int count = 3;
        List<Long> orderNoList = mallOrderMapper.selectSomeLatestOrderNoByIdList(count, getCustomerUserIdList(customerId), HAVE_PAY, HAVE_SEND, HAVE_FINISH);
        Map<String, BigDecimal> countMap = new HashMap<>(20);
        List<MallOrderItem> mallOrderItemList;
        if (orderNoList.size() != 0) {
            mallOrderItemList = mallOrderItemMapper.selectByOrderNoListWithLong(orderNoList);

            for (MallOrderItem mallOrderItem : mallOrderItemList) {
                String type = mallOrderItem.getProductName().split(",", -1)[0];
                BigDecimal quantity = mallOrderItem.getQuantity();
                if (countMap.get(type) == null) {
                    countMap.put(type, quantity);
                } else {
                    countMap.put(type, countMap.get(type).add(quantity));
                }
            }
        }
        String likeProductType = "";
        BigDecimal maxQuantity = new BigDecimal(0.0);
        for (Object o : countMap.entrySet()) {
            Map.Entry entry = (Map.Entry) o;
            String key = (String) entry.getKey();
            BigDecimal value = (BigDecimal) entry.getValue();
            if (value.doubleValue() > maxQuantity.doubleValue()) {
                likeProductType = key;
                maxQuantity = value;
            }
        }
        SysCustomerUserIsStar sysCustomerUserIsStar = sysCustomerUserIsStarMapper.selectIsStar(salesmanId, customerId);
        //0orNull代表普通客户 1代表星标客户
        Boolean isStar = sysCustomerUserIsStar != null && (sysCustomerUserIsStar.getIsStar() == 1);

        Integer creditScore = 5;

        //暂时写死
        Integer accountPeriod = 0;

        String salesmanUserName = userMapper.selectByPrimaryKey(salesmanId).getRealName();

        CustomerUserInformation customerUserInformation = new CustomerUserInformation(registerTime, username.split("-")[0], customerCity, likeProductType, user.getUsername(), isStar, creditScore, accountPeriod, salesmanUserName);
        int customerType = 0;
        SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customerId);
        if(null != sysCustomerCredit) {
            customerType = 1;
        }
        customerUserInformation.setCustomerType(customerType);
        int quota = 0;
        if(1 == customerType){
            quota = sysCustomerCredit.getQuota();
            accountPeriod = sysCustomerCredit.getAccountPeriod();
        }
        customerUserInformation.setAcountPeriod(accountPeriod);
        customerUserInformation.setQuota(quota);
        return customerUserInformation;

    }


    /**
     * @Date 2018/11/8 15:29
     * @Param [customerId]
     * @return com.hmall.vo.CustomerTradeInformation
     * @Description // 得到公司的交易信息
     */
    private CustomerTradeInformation getCustomerTradeInformation(Integer customerId){

        Integer historyOrderNumber = mallOrderMapper.selectOrderCountByUserIdList(getCustomerUserIdList(customerId), HAVE_PAY, HAVE_SEND, HAVE_FINISH);

        //历史消费
        BigDecimal historyPayment = new BigDecimal(0);

        //暂无设计

        //2018/9/29要计算

        //历史还款总额
        BigDecimal returnPayment = new BigDecimal(0);

        List<SysCustomerStatement> sysCustomerStatementList = sysCustomerStatementMapper.selectByCustomerId(customerId);
        for(SysCustomerStatement customerStatement : sysCustomerStatementList){
            historyPayment = historyPayment.add(customerStatement.getThisMonthFufillmentPayment());
            returnPayment = returnPayment.add(customerStatement.getThisMonthReturnPayment());
        }


        BigDecimal lastReturnPayment = new BigDecimal(0);

        Date lastReturnTime = null;


        //找到这个公司下的用户最近的一个通过的凭证
        MallPaymentVoucher mallPaymentVoucher = mallPaymentVoucherMapper.selectLatestVoucher(customerId);
        if(null != mallPaymentVoucher){
            lastReturnTime = mallPaymentVoucher.getCreateTime();
            lastReturnPayment = mallPaymentVoucher.getFactPayment();
        }


        Integer refundOrderNumber = 0;

        BigDecimal refundOrderPayment = new BigDecimal(0);

        return new CustomerTradeInformation(historyOrderNumber, historyPayment, returnPayment, lastReturnPayment, lastReturnTime, refundOrderNumber, refundOrderPayment);
    }

    /**
     * @Date 2018/11/8 14:25
     * @Param [customerId]
     * @return java.util.List<java.lang.Integer>
     * @Description // 根据客户得到客户下的所有用户列表
     */
    private List<Integer> getCustomerUserIdList(Integer customerId) {

        return sysUserDeptMapper.selectUserIdListByCustomerId(customerId);
    }

    /**
     * @Date 2018/11/8 14:25
     * @Param [salesmanId] 
     * @return java.util.List<java.lang.Integer>
     * @Description // 根据办事员得到办事员绑定的客户       
     */
    private List<Integer> getCustomerIdList(Integer salesmanId) {

        return customerMapper.selectCustomerIdLisstBySalsemanId(salesmanId);
    }

    /**
     * @Date 2018/11/8 14:26
     * @Param [deptId] 
     * @return java.util.List<java.lang.Integer>
     * @Description // 得到办事处下所有的业务员       
     */
    private List<Integer> getSalesmanIdList(Integer deptId) {

        return userMapper.selectUserIdListByDeptId(deptId);
    }

    /**
     * @Date 2018/11/8 14:26
     * @Param [userId, customerId] 
     * @return com.hmall.common.ServerResponse
     * @Description // 改变公司星标类型       
     */
    public ServerResponse changeStar(Integer userId, Integer customerId) {

        //先查找是否有
        SysCustomerUserIsStar sysCustomerUserIsStar = sysCustomerUserIsStarMapper.selectIsStar(userId, customerId);

        //1.如果null 更新为1 进行插入
        //2.如果0更新 1
        //3.如果1 更新0
        int isStar;
        if (sysCustomerUserIsStar == null) {
            isStar = 1;
            sysCustomerUserIsStarMapper.insertStarStatus(userId, customerId, isStar);
        } else {
            isStar = 1 - sysCustomerUserIsStar.getIsStar();
            sysCustomerUserIsStarMapper.updateStarStatus(userId, customerId, isStar);
        }

        return ServerResponse.createBySuccessMessage("更新成功");
    }

   /**
    * @Date 2018/11/8 14:26
    * @Param [fuzzyModel, shopId, pageNum, pageSize] 
    * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo>
    * @Description //
    *  要匹配批号
    *    从连接表里先取出匹配到的批号列表 得到productIdList
    *    在列出产品列表
    *    1.要保证和compete接口保持一致
    *    2.保证速度，先找出priceIdList 对这个进行分页批量查询
    */
    public ServerResponse<PageVo<ShortCompete>> competeByFuzzyModel(String fuzzyModel, Integer shopId, Integer pageNum, Integer pageSize) {

        //产品
        List<Integer> productIdList = mallAttrConnectMapper.findProductIdListByFuzzyModel(fuzzyModel, shopId);

        //真实产品数目判断依据
        List<Integer> priceIdList = new ArrayList<>();
        if (productIdList.size() != 0) {
            priceIdList = mallPriceMapper.findPriceIdListByProductIdList(productIdList);
        }
        List<ShortCompete> shortCompeteList = new ArrayList<>();

        //假分页  因为name的原因 不会写sql函数
        Integer total = priceIdList.size();
        Integer pageStart = (pageNum - 1) * pageSize;
        Integer pageEnd = Math.min(total, pageStart + pageSize);
        List<Integer> subPriceIdList = priceIdList.subList(pageStart, pageEnd);


        List<MallPrice> subMallPriceList = new ArrayList<>();
        if (subPriceIdList.size() != 0) {
            subMallPriceList = mallPriceMapper.selectByPriceIdList(subPriceIdList);
        }

        for (MallPrice mallPrice : subMallPriceList) {

            int productId = mallPrice.getProductId();
            ShortCompete shortCompete = new ShortCompete();
            //不建议 如果无该公司是会报错
            shortCompete.setShopName(mallShopMapper.selectByPrimaryKey(shopId).getShopName());

            //可以优化点 不必全查数据库 pageSize足够小没必要
            MallProduct mallProduct = mallProductMapper.selectByPrimaryKey(productId);
            shortCompete.setImg(mallProduct.getMainImage().split(",")[0]);
            shortCompete.setPrice(mallProduct.getPrice());
            shortCompete.setStock(mallProduct.getStock());
            shortCompete.setName(mallProduct.getName());
            shortCompete.setUnit("千克");
            shortCompete.setProductId(productId);
            shortCompete.setNew(mallProduct.getIsnew() == 1);
            List<MallPrice> mallPriceList = mallPriceMapper.selectByProductId(mallPrice.getProductId());
            shortCompete.setComPrice(mallPriceList);
            shortCompete.setGrade(mallPrice.getGrade());

            shortCompeteList.add(shortCompete);
        }

        PageVo<ShortCompete> pageVo = new PageVo<>(pageNum, pageSize, total, shortCompeteList);
        return ServerResponse.createBySuccess(pageVo);
    }

    /**
     * @Date 2018/11/8 15:06
     * @Param [userId, customerUserId, status, pageNum, pageSize]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo>
     * @Description // 列出订单列表
     */
    public ServerResponse<Object> listNormalOrderList(Integer userId, Integer customerUserId, String status, Integer pageNum, Integer pageSize) {



        //得到所有和这个业务员相关连的用户信息
        List<Integer> customerUserIdList = getCustomerIdListByBackUserId(userId, customerUserId);

        List<MallOrder> mallOrderList = new ArrayList<>();
        if(customerUserIdList.size() != 0) {
            mallOrderList = mallOrderMapper.selectOrderIdByUserIdList(customerUserIdList);
        }

        int intStatus = -1;
        if("全部".equals(status) || "拿样".equals(status)){
            intStatus = -1;
        }else if("待审核".equals(status)){
            intStatus = 10;
        }else if("待发货".equals(status)){
            intStatus = 20;
        }else if("交易完成".equals(status)){
            intStatus = 50;
        }else if("待发货".equals(status)){
            intStatus = 30;
        }else if("已发货".equals(status)){
            intStatus = 60;
        }else if("已取消".equals(status)){
            intStatus = 0;
        }

        List<MallOrder> subMallOrderList = new ArrayList<>();
        if(intStatus != -1) {
            for (MallOrder mallOrder : mallOrderList) {
                if (intStatus == mallOrder.getStatus()) {
                        subMallOrderList.add(mallOrder);
                }
            }
            mallOrderList = subMallOrderList;
        }

        List<MallOrder> ssubMallOrderList = new ArrayList<>();
        //筛选一遍拿样
        if("拿样".equals(status)){
            for(MallOrder mallOrder : mallOrderList){
                if(mallOrder.getIsSample() == 1){
                    ssubMallOrderList.add(mallOrder);
                }
            }
            mallOrderList = ssubMallOrderList;
        }



        int total = mallOrderList.size();
        int pageStart = pageSize * (pageNum - 1);
        int pageEnd = Math.min(total, pageStart + pageSize);
        mallOrderList = mallOrderList.subList(pageStart, pageEnd);

        List<OrderVo> orderVoList = new ArrayList<>();
        String normalOrderStr = "全部" + "待审核" + "待发货" + "交易完成" + "付款凭证未上传" + "付款凭证未审核" + "已取消" + "已发货";
        for (MallOrder mallOrder : mallOrderList) {
            int flag = 0;
            OrderVo orderVo = null;
            //如果是普通订单
            String type = "list";
            if (mallOrder.getIsSample() == 0) {
                if (normalOrderStr.contains(status)) {
                    boolean check = "全部".equals(status)
                            || ("待审核".equals(status) && mallOrder.getStatus() == 10)
                            || ("待发货".equals(status) && mallOrder.getStatus() == 20)
                            || ("交易完成".equals(status) && mallOrder.getStatus() == 50)
                            || ("待发货".equals(status) && mallOrder.getStatus() == 30)
                            || ("待发货".equals(status) && mallOrder.getStatus() == 70)
                            || ("已取消".equals(status) && mallOrder.getStatus() == 0)
                            || ("已发货".equals(status) && mallOrder.getStatus() == 60);
                    if (check){
                        flag = 1;
                        orderVo = changeMallOrderToOrderVo(mallOrder, null, type);
                    }

                }
                //不包括申诉，差评，退换货
            } else {
                //如果是拿样订单
                if ("拿样".equals(status)) {
                    flag = 1;
                    orderVo = changeMallOrderToOrderVo(mallOrder, null, type);
                }
            }
             /*业务员：待审核  待审核（跟单员审核中） 待审核（跟单员驳回） 待审核（资金专员驳回）
          跟单员：    待审核      待审核（资金专员未审核）   待发货
          资金专员：  待审核                                 待发货*/

            Integer deptId = userMapper.selectByPrimaryKey(userId).getDeptId();
            Integer roleId = sysUserRoleMapper.selectRole(userId).getRoleId();
            String detailStatus = MerchUtil.getDetailStatus(userId, deptId, roleId, mallOrder);


          //  if (orderVo != null) {
                if(orderVo == null) {
                    orderVo = new OrderVo();
                    orderVo.setDetialStatus("该订单的用户被删除");
                }else {
                    orderVo.setDetialStatus(detailStatus);
                }
                if(flag == 1) {
                    orderVoList.add(orderVo);
                }
          //  }
        }

        PageVo<OrderVo> pageVo = new PageVo<>(pageNum, pageSize, total, orderVoList);
        return ServerResponse.createBySuccess(JSON.toJSON(pageVo));
    }


    /**
     * @Date 2018/11/8 15:09
     * @Param [userId, customerUserId]
     * @return java.util.List<java.lang.Integer>
     * @Description // 后台业务员得到所有与其办事处绑定的客户信息，支持单选和全选
     */
    private List<Integer> getCustomerIdListByBackUserId(Integer userId, Integer customerUserId){

        //1.先根据用户查看拥有什么权限
        List<String> menuList = menuMapper.listMenuByUserId(userId);
        int role = DealerMenuUtil.getBackRole(menuList);

        List<Integer> salesmanIdList = new ArrayList<>();
        if (role == 0) {
            //对于业务员
            salesmanIdList.add(userId);
        } else if(role == 1){
            //业务员列表
            salesmanIdList = getSalesmanIdList(userMapper.selectByPrimaryKey(userId).getDeptId());
        }else{
            return null;
        }

        //先列出所有的订单遍历一遍进行处理
        //得到了业务员列表——>业务员绑定的所有用户

        List<Integer> customerIdList = new ArrayList<>();
        for (Integer salesmanId : salesmanIdList) {
            customerIdList.addAll(customerMapper.selectCustomerIdLisstBySalsemanId(salesmanId));
        }
        Set<Integer> set = new HashSet<>(customerIdList);
        customerIdList.clear();
        customerIdList.addAll(set);

        List<Integer> customerUserIdList = new ArrayList<>();
        for (Integer customerId : customerIdList) {
            customerUserIdList.addAll(getCustomerUserIdList(customerId));
        }
        set.clear();
        set.addAll(customerUserIdList);
        customerUserIdList.clear();
        customerUserIdList.addAll(set);

        if (customerUserId != null) {
            customerUserIdList.clear();
            customerUserIdList.add(customerUserId);
        }
        return customerUserIdList;

    }


    private Integer getPlanDBStatus(Integer status) {

        int planDBStatus = -1;
        if (status == null) {
            return planDBStatus;
        }
        switch (status) {
            case 1: {
                break;
            }
            case 2: {
                planDBStatus = 1;
                break;
            }
            case 3: {
                planDBStatus = 2;
                break;
            }
            case 4: {
                planDBStatus = 3;
                break;
            }
            case 5: {
                planDBStatus = 1;
                break;
            }
            case 7: {
                planDBStatus = 0;
                break;
            }
            default:{
                break;
            }
        }

        return planDBStatus;
    }

    


    /**
     * @Date 2018/11/8 14:36
     * @Param [userId, orderNo, status] 
     * @return com.hmall.common.ServerResponse<com.hmall.vo.OrderDetialVo>
     * @Description // 得到订单详情       
     */
    public ServerResponse<Object> getOrderDetail(Integer userId, Long orderNo, String status, Long groupNo) {

        OrderDetialVo orderDetialVo = new OrderDetialVo();

        MallOrder mallOrder = mallOrderMapper.selectAllByOrderNo(orderNo);

        orderDetialVo.setIsSample(mallOrder.getIsSample());
        //地址显示
        MallShipping mallShipping = mallShippingMapper.selectByShippingId(mallOrder.getShippingId());
        MallShippingVo mallShippingVo = new MallShippingVo();
        if(null != mallShipping){
            mallShippingVo = new MallShippingVo(mallShipping.getId(), mallShipping.getReceiverName(), mallShipping.getReceiverMobile(), mallShipping.getReceiverPhone(), mallShipping.getDefaultCheck(), mallShipping.getReceiverProvince(), mallShipping.getReceiverCity(), mallShipping.getReceiverDistrict(), mallShipping.getReceiverAddress());
        }
        //暂时只能一部分
        int dbStatus = mallOrder.getStatus();

        orderDetialVo.setStatus(status);
        orderDetialVo.setStatusNumber(dbStatus);
        orderDetialVo.setMallShippingVo(mallShippingVo);
        OrderVo orderVo = changeMallOrderToOrderVo(mallOrder, groupNo);

        //设置话，在前端显示
        /*业务员：待审核  待审核（跟单员审核中） 待审核（跟单员驳回） 待审核（资金专员驳回）
          跟单员：    待审核      待审核（资金专员未审核）   待发货
          资金专员：  待审核                                 待发货*/

        Integer deptId = userMapper.selectByPrimaryKey(userId).getDeptId();
        Integer roleId = sysUserRoleMapper.selectRole(userId).getRoleId();
        String detailStatus = MerchUtil.getDetailStatus(userId, deptId, roleId, mallOrder);

        orderVo.setDetialStatus(detailStatus);
        orderDetialVo.setOrderVo(orderVo);
        orderDetialVo.setDistName(mallDistmodeMapper.selectByPrimaryKey(mallOrder.getDistcode()).getDistName());
        orderDetialVo.setMessage(mallOrder.getMessage());

        SysCustomer customer = customerMapper.selectByUserId(mallOrder.getUserId());
        //发票信息
        InvoiceVo invoiceVo = new InvoiceVo(customer.getInvoiceTitle(), customer.getTaxNum(), customer.getBankName(), customer.getBankNumber(), mallOrder.getInvoiceRecPerson(), mallOrder.getInvoiceRecPhone(), mallOrder.getInvoiceRecAddress());
        orderDetialVo.setInvoiceVo(invoiceVo);
        orderDetialVo.setTotalPrice(orderVo.getTotalPrice());
        orderDetialVo.setPayment(orderVo.getPayment());
        orderDetialVo.setSaleContNo(orderVo.getSaleContNo());

        //得到发货详情
        List<OrderSendVo> orderSendVoList = getOrderSendVoList(orderNo);
        log.info("得到发货详情成功");
        orderDetialVo.setOrderSendVoList(orderSendVoList);
        orderDetialVo.setMessage(mallOrder.getMessage());

        //得到备注信息,包括用户自己的留言以及审核的意见
        List<OrderRemarkVo> orderRemarkVoList = getOrderRemarkVoList(mallOrder);
        log.info("得到备注信息成功");

        orderDetialVo.setStatusOne(mallOrder.getStatus1());
        orderDetialVo.setStatusTwo(mallOrder.getStatus2());
        orderDetialVo.setStatusThree(mallOrder.getStatus3());
        orderDetialVo.setExamOpinion(orderRemarkVoList);
        return ServerResponse.createBySuccess(JSON.toJSON(orderDetialVo));
    }

    public ServerResponse getSubOrderDetail(Integer userId, Long orderNo, Long groupNo, String status){

        return getOrderDetail(userId, orderNo, status, groupNo);

    }


    /**
     * @Date 2018/11/8 15:48
     * @Param [orderNo]
     * @return java.util.List<com.hmall.vo.OrderSendVo>
     * @Description // 根据订单得到发货列表
     */
    private List<OrderSendVo> getOrderSendVoList(Long orderNo){

        List<OrderSendVo> orderSendVoList = new ArrayList<>();
        List<MallOrderFufillmentParent> mallOrderFufillmentParentList = mallOrderFufillmentParentMapper.selectByOrderNo(orderNo);
        if (mallOrderFufillmentParentList.size() != 0) {
            for (MallOrderFufillmentParent mallOrderFufillmentParent : mallOrderFufillmentParentList) {
                OrderSendVo orderSendVo = new OrderSendVo();

                String fufillmentNo = mallOrderFufillmentParent.getFufillmentNo();
                List<ProductFufillmentVo> productFufillmentVoList = new ArrayList<>();
                List<MallOrderFufillment> mallOrderFufillmentList = mallOrderFufillmentMapper.selectByFufillmentNo(fufillmentNo);
                for (MallOrderFufillment mallOrderFufillment : mallOrderFufillmentList) {
                    ProductFufillmentVo productFufillmentVo = new ProductFufillmentVo();
                    productFufillmentVo.setModel(mallOrderFufillment.getModel());
                    MallOrderItem mallOrderItem = mallOrderItemMapper.selectByPrimaryKey(mallOrderFufillment.getOrderItemId());
                    if(mallOrderItem == null) {
                        continue;
                    }
                    Integer productId = mallOrderItem.getProductId();
                    productFufillmentVo.setProductId(productId);
                    productFufillmentVo.setWeight(mallOrderFufillment.getWeight());
                    productFufillmentVo.setName(mallOrderItem.getProductName());
                    productFufillmentVo.setImg(mallOrderItem.getProductImage().split(",")[0]);
                    productFufillmentVo.setGrade(mallOrderItem.getGrade());
                    productFufillmentVoList.add(productFufillmentVo);
                }
                orderSendVo.setProductFufillmentVoList(productFufillmentVoList);
                orderSendVo.setAddress(mallOrderFufillmentParent.getAddress());

                orderSendVo.setIsReceive(mallOrderFufillmentParent.getIsReceived());
                orderSendVo.setRemark(mallOrderFufillmentParent.getRemark());
                orderSendVo.setOrderFufillmentNo(mallOrderFufillmentParent.getFufillmentNo());
                orderSendVo.setSendTime(mallOrderFufillmentParent.getCreateTime());

                orderSendVoList.add(orderSendVo);
            }
        }
        return  orderSendVoList;
    }


    /**
     * @Date 2018/11/8 15:50
     * @Param [mallOrder]
     * @return java.util.List<com.hmall.vo.OrderRemarkVo>
     * @Description // 得到备注信息列表
     */
    private List<OrderRemarkVo> getOrderRemarkVoList(MallOrder mallOrder){

        //2018/11/22现在是备注列表
        //根据orderNo找到groupNo
        List<Long> groupNoList = mallOrderItemDetailMapper.selectGroupNoListByOrderNo(mallOrder.getOrderNo());

        //审核的备注被插入这个表里面
        List<OrderRemarkVo> orderRemarkVoList = new ArrayList<>();
        List<MallOrderRemark> mallOrderRemarkList = new ArrayList<>();
        for(Long groupNo : groupNoList) {
            mallOrderRemarkList.addAll(mallOrderRemarkMapper.selectByOrderNoWithType(groupNo, -1));
        }
        for(MallOrderRemark mallOrderRemark : mallOrderRemarkList){
            OrderRemarkVo tOrderRemarkVo = new OrderRemarkVo();
            tOrderRemarkVo.setCreateTime(mallOrderRemark.getCreateTime());
            tOrderRemarkVo.setType(mallOrderRemark.getType());
            tOrderRemarkVo.setUserId(mallOrderRemark.getUserId());
            tOrderRemarkVo.setUserName(userMapper.selectByPrimaryKey(mallOrderRemark.getUserId()).getRealName());
            tOrderRemarkVo.setOrderNo(mallOrderRemark.getOrderNo());
            tOrderRemarkVo.setOpinion(mallOrderRemark.getContent());
            orderRemarkVoList.add(tOrderRemarkVo);
        }
        OrderRemarkVo orderRemarkVo = new OrderRemarkVo();
        orderRemarkVo.setCreateTime(mallOrder.getCreateTime());
        orderRemarkVo.setType(0);
        orderRemarkVo.setOpinion(mallOrder.getMessage());
        orderRemarkVo.setOrderNo(mallOrder.getOrderNo());

        //创建订单入口1.用户 2.业务员
        //订单的备注
        if(mallOrder.getSubmitPerson() == 1) {
            orderRemarkVo.setUserId(mallOrder.getUserId());
            orderRemarkVo.setUserName(userMapper.selectByPrimaryKey(mallOrder.getUserId()).getRealName());
        }
        else {
            Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(mallOrder.getUserId());
            Integer salesmanId = customerMapper.selectByPrimaryKey(customerId).getSalesmanId();
            String userName = userMapper.selectByPrimaryKey(salesmanId).getRealName();
            orderRemarkVo.setUserId(salesmanId);
            orderRemarkVo.setUserName(userName);
        }

        //审核备注 可以多条
        orderRemarkVoList.add(orderRemarkVo);
        return orderRemarkVoList;
    }

    private OrderVo changeMallOrderToOrderVo(MallOrder mallOrder, Long groupNo){

        return changeMallOrderToOrderVo(mallOrder, groupNo, "detail");
    }

    private OrderVo changeMallOrderToOrderVo(MallOrder mallOrder) {
        return changeMallOrderToOrderVo(mallOrder, null);
    }
    /**
     * @Date 2018/11/8 14:38
     * @Param [mallOrder]
     * @return com.hmall.vo.OrderVo
     * @Description // 将order重新封装成orderVo type list或者detail
     */
    private OrderVo changeMallOrderToOrderVo(MallOrder mallOrder, Long groupNo, String type) {

        OrderVo orderVo = new OrderVo();
        //可以数据库 left join 优化 如果时间过长
        SysDeptCustomer sysDeptCustomer;
        sysDeptCustomer = sysDeptCustomerMapper.selectAllByCustomerUserId(mallOrder.getUserId());
        if (sysDeptCustomer != null) {
            Integer customerId = sysDeptCustomer.getCustomerId();
            orderVo.setCustomerId(customerId);
            orderVo.setPlanCheck(mallOrder.getPlanCheck());
            orderVo.setCustomerName(customerMapper.selectByPrimaryKey(customerId).getBusName());
            SysUser user = userMapper.selectByPrimaryKey(mallOrder.getUserId());
            String realName;
            if (user == null) {
                realName = "该用户不存在";
            } else {
                realName = user.getRealName();
            }
            orderVo.setCustomerUserName(realName);
        }

        orderVo.setCustomerUserId(mallOrder.getUserId());
        orderVo.setUpdateTime(mallOrder.getUpdateTime());
        orderVo.setCreateTime(mallOrder.getCreateTime());
        orderVo.setOrderNo(mallOrder.getOrderNo());
        orderVo.setSubmitPerson(mallOrder.getSubmitPerson());
        orderVo.setDistCode(mallOrder.getDistcode());
        orderVo.setSendDate(mallOrder.getSendDate());
        orderVo.setStatusOne(mallOrder.getStatus1());
        orderVo.setStatusTwo(mallOrder.getStatus2());
        orderVo.setSalesOrganization(mallOrder.getSalesOrganization());
        orderVo.setSalesType(mallOrder.getSalesType());
        orderVo.setPaymentMethods(mallOrder.getPaymentMethods());
        orderVo.setFreightPaymentType(mallOrder.getFreightPaymentType());
        orderVo.setStatusThree(mallOrder.getStatus3());
        orderVo.setMallTransport(mallTransportMapper.selectByPrimaryKey(mallOrder.getTransportId()));
        String status;
        if (mallOrder.getIsSample() == 0) {
            int dbStatus = mallOrder.getStatus();
            if (Const.ORDER_WAIT_EXAM.equals(dbStatus)) {
                status = "待审核";
            } else if (Const.ORDER_CANCEL.equals(dbStatus)) {
                status = "已取消";
            } else if (Const.ORDER_WAIT_SEND.equals(dbStatus)) {
                status = "待发货";
            } else if (Const.ORDER_SENDING.equals(dbStatus)) {
                status = "已发货";
            } else if (Const.ORDER_FINISH.equals(dbStatus)) {
                status = "交易完成";
            } else {
                status = "无效的状态，合同残留，分期残留";
            }
        } else {
            status = "拿样";
        }
        orderVo.setStatus(status);

        BigDecimal totalPrice = new BigDecimal(0.0);

        List<OrderItemVo> orderItemVoList = new ArrayList<>();
        List<MallOrderItem> mallOrderItemList = mallOrderItemMapper.selectAllByOrderNo(mallOrder.getOrderNo());

        List<MallProductForwardFormateVo> subMallProductForwardStockList = new ArrayList<>();

        //2018/11/20 需要分组
        //2018/11/21 又不需要分组了
        //需求不明确，lj
        //不带J的
        List<MallProductForwardFormateParentVo> mallProductForwardFormateParentVoList = new ArrayList<>();
        //带J的
        Map<Long, List<OrderItemDetialVo>> map = new HashMap<>(16);


        for (MallOrderItem mallOrderItem : mallOrderItemList) {

            int count = 0;
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setGrade(mallOrderItem.getGrade());
            String imgUrl = mallOrderItem.getProductImage();
            if (imgUrl.contains(",")) {
                imgUrl = imgUrl.split(",")[0];
            }
            orderItemVo.setImg(imgUrl);
            orderItemVo.setProductId(mallOrderItem.getProductId());
            orderItemVo.setModel(mallOrderItem.getProductName().split(",", -1)[2]);
            orderItemVo.setPrice(mallOrderItem.getTotalPrice());
            orderItemVo.setUnitPrice(mallOrderItem.getCurrentUnitPrice());

            orderItemVo.setName(mallOrderItem.getProductName());
            orderItemVo.setWeight(mallOrderItem.getQuantity());
            orderItemVo.setOrderItemId(mallOrderItem.getId());
            orderItemVo.setColor(mallOrderItem.getProductName().split(",", -1)[7]);
            orderItemVo.setResidualQuantity(mallOrderItem.getResidualQuantity());
            totalPrice = totalPrice.add(mallOrderItem.getTotalPrice());

            //2018/10/18 加库存需求
            List<MallProductForwardStock> tMallProductForwardStockList = new ArrayList<>();
            String[] nameStr = mallOrderItem.getProductName().split(",", -1);
            if ("detail".equals(type)) {

                //根据model，捻度和等级得到库存列表
                String[] arr1 = {"AA1定重", "AA2定重", "AA3定重", "AA5定重", "AA6定重", "AA7定重", "AA定重"};
                String[] arr2 = {"AA1不定重", "AA2不定重", "AA3不定重", "AA5不定重", "AA6不定重", "AA7不定重", "AA不定重"};
                if ("AA定重".equals(mallOrderItem.getGrade())) {
                    for (String grade : arr1) {
                        //
                        tMallProductForwardStockList.addAll(getProductForwardStockInformation(nameStr[2], nameStr[9], grade, nameStr[6]).getData());
                    }
                } else if ("AA不定重".equals(mallOrderItem.getGrade())) {
                    for (String grade : arr2) {
                        tMallProductForwardStockList.addAll(getProductForwardStockInformation(nameStr[2], nameStr[9], grade, nameStr[6]).getData());
                    }
                } else {
                    tMallProductForwardStockList = getProductForwardStockInformation(nameStr[2], nameStr[9], mallOrderItem.getGrade(), nameStr[6]).getData();
                }

                //遍历之后插入改物料编码下的产品重量和价格
                Integer orderItemId = mallOrderItem.getId();

                List<MallOrderItemDetail> mallOrderItemDetailList = mallOrderItemDetailMapper.selectList(orderItemId);
                if (groupNo != null) {
                    List<MallOrderItemDetail> newMallOrderItemDetailList = new ArrayList<>();
                    for (MallOrderItemDetail mallOrderItemDetail : mallOrderItemDetailList) {
                        if (mallOrderItemDetail.getGroupNo().equals(groupNo)) {
                            newMallOrderItemDetailList.add(mallOrderItemDetail);
                        }
                    }
                    mallOrderItemDetailList.clear();
                    mallOrderItemDetailList.addAll(newMallOrderItemDetailList);
                }
//


                List<MallProductForwardFormateVo> mallProductForwardStockList = new ArrayList<>();
                List<MallProductForwardWithGrade> mallProductForwardWithGradeList = new ArrayList<>();
                Map<String, List<MallProductForwardFormateVo>> gradeMap = new HashMap<>(16);

                //纯库存信息

                //2018/12/7 校验订单去重

                //2019/1/14 尝试修改逻辑
                //如果status不为10则直接列出订单detail信息
                Set<String> materialCodeSet = new HashSet<>();
                List<String> gradeList = new ArrayList<>();
                if (mallOrder.getStatus() != 10) {
                    for (MallOrderItemDetail mallOrderItemDetail : mallOrderItemDetailList) {
                        MallProductForwardFormateVo mallProductForwardFormateVo = new MallProductForwardFormateVo();
                        mallProductForwardFormateVo.setMaterialCode(mallOrderItemDetail.getMaterialCode());
                        mallProductForwardFormateVo.setInventoryOrganization(mallOrderItemDetail.getInventoryOrganization());


                        mallProductForwardFormateVo.setPrice(mallOrderItemDetail.getCurrentUnitPrice());
                        mallProductForwardFormateVo.setWeight(mallOrderItemDetail.getQuantity());
                        mallProductForwardFormateVo.setRate(mallOrderItemDetail.getRate());
                        mallProductForwardFormateVo.setResidualQuantity(mallOrderItem.getResidualQuantity());
                        mallProductForwardFormateVo.setOrderItemId(mallOrderItem.getId());
                        mallProductForwardFormateVo.setExFactoryPrice(mallOrderItemDetail.getExFactoryPrice());
                        mallProductForwardFormateVo.setFreightPaymentType(mallOrderItemDetail.getFreightPaymentType());
                        mallProductForwardFormateVo.setSalesOrganization(mallOrderItemDetail.getSalesOrganization());
                        mallProductForwardFormateVo.setPaymentMethods(mallOrderItemDetail.getPaymentMethods());
                        mallProductForwardFormateVo.setSalesType(mallOrderItemDetail.getSalesType());
                        mallProductForwardFormateVo.setGroupNo(mallOrderItemDetail.getGroupNo());
                        mallProductForwardFormateVo.setCheckQuantity(mallOrderItemDetail.getCheckQuantity());
                        mallProductForwardFormateVo.setMachineNo(mallOrderItemDetail.getMachineNo());
                        mallProductForwardFormateVo.setGrade(mallOrderItemDetail.getGrade());
                        mallProductForwardFormateVo.setColor(mallOrderItemDetail.getColor());
                        mallProductForwardFormateVo.setTwisting(mallOrderItemDetail.getTwisting());

                        //保留原来的
                        //如果是审核之前的是库存列表之后是产品列表

                        //如果是审核之后如果count = 0那么不加
                        //如果是审核之前都加
                        //    boolean check = (mallOrder.getStatus() == 10) || (mallOrder.getStatus() != 10 && count != 0);
//                        if (check) {
                        mallProductForwardStockList.add(mallProductForwardFormateVo);
                        //2018/11/23现在要拆分等级
                        List<MallProductForwardFormateVo> mallProductForwardFormateVoList = gradeMap.get(mallProductForwardFormateVo.getGrade());
                        if (mallProductForwardFormateVoList == null) {
                            mallProductForwardFormateVoList = new ArrayList<>();
                        }
                        mallProductForwardFormateVoList.add(mallProductForwardFormateVo);
                        gradeMap.put(mallProductForwardFormateVo.getGrade(), mallProductForwardFormateVoList);
//                        }

                        orderItemVo.setMallProductForwardStockList(mallProductForwardStockList);

                        //得到所有的库存列表
                        MallProductForwardFormateVo subMallProductForwardStock = new MallProductForwardFormateVo(mallProductForwardFormateVo.getId(), mallProductForwardFormateVo.getInventoryOrganization(),
                                mallProductForwardFormateVo.getFactory(), mallProductForwardFormateVo.getMaterialCode(), mallProductForwardFormateVo.getMaterialName(), mallProductForwardFormateVo.getSpecifications(), mallProductForwardFormateVo.getModel(),
                                mallProductForwardFormateVo.getGradeInfo(), mallProductForwardFormateVo.getMachineType(), mallProductForwardFormateVo.getNetworkPly(), mallProductForwardFormateVo.getGrade(), mallProductForwardFormateVo.getTwisting(),
                                mallProductForwardFormateVo.getStatus(), mallProductForwardFormateVo.getCanBuyNumber(), mallProductForwardFormateVo.getBuyNumber(), mallProductForwardFormateVo.getSendNumber(), mallProductForwardFormateVo.getWaitOutNumber(),
                                mallProductForwardFormateVo.getWaitInNumber(), mallProductForwardFormateVo.getStock(), mallProductForwardFormateVo.getStockBoxNumber(), mallProductForwardFormateVo.getSortCode(), mallProductForwardFormateVo.getSortName(), mallProductForwardFormateVo.getPrice(),
                                mallProductForwardFormateVo.getWeight(), mallProductForwardFormateVo.getRate(), mallProductForwardFormateVo.getExFactoryPrice(), mallProductForwardFormateVo.getResidualQuantity(), mallProductForwardFormateVo.getSalesOrganization(),
                                mallProductForwardFormateVo.getSalesType(), mallProductForwardFormateVo.getFreightPaymentType(), mallProductForwardFormateVo.getPaymentMethods(), mallProductForwardFormateVo.getGroupNo());
                        subMallProductForwardStock.setCheckQuantity(mallProductForwardFormateVo.getCheckQuantity());
                        subMallProductForwardStock.setTwisting(mallProductForwardFormateVo.getTwisting());
                        subMallProductForwardStock.setColor(mallProductForwardFormateVo.getColor());
                        subMallProductForwardStock.setMachineNo(mallProductForwardFormateVo.getMachineNo());
                        subMallProductForwardStock.setGrade(mallProductForwardFormateVo.getGrade());
                        boolean checkSubOrder = mallOrderItemDetailList.size() == 0;
                        //如果是待审核状态,直接pass
                        //目前如果待审核就不会有子订单
                        if (mallOrder.getStatus() == 10) {
                            subMallProductForwardStock = null;
                        }

                        if (subMallProductForwardStock != null) {
                            //如果是审核状态并且存在子订单
                            if (mallOrder.getStatus() == 10 && !checkSubOrder) {
                                subMallProductForwardStockList.add(subMallProductForwardStock);
                            } else if (mallOrder.getStatus() != 10) {
                                //如果是审核通过状态
                                subMallProductForwardStockList.add(subMallProductForwardStock);
                            }
                        }

                        materialCodeSet.clear();

                        //把map封装成一个list
                        gradeMap.forEach((key, value) -> {
                            MallProductForwardWithGrade mallProductForwardWithGrade = new MallProductForwardWithGrade();
                            mallProductForwardWithGrade.setGrade(key);
                            mallProductForwardWithGrade.setMallProductForwardStockList(value);
                            mallProductForwardWithGradeList.add(mallProductForwardWithGrade);
                            gradeList.add(key);
                        });
                    }
                } else {
                    for (MallProductForwardStock tMallProductForwardStock : tMallProductForwardStockList) {
                        //保证前端数据不变 变量名很怪
                        //库存的信息
                        MallProductForwardFormateVo mallProductForwardFormateVo = new MallProductForwardFormateVo(tMallProductForwardStock.getId(), tMallProductForwardStock.getInventoryOrganization(), tMallProductForwardStock.getFactory(), tMallProductForwardStock.getMaterialCode(), tMallProductForwardStock.getMaterialName(),
                                tMallProductForwardStock.getSpecifications(), tMallProductForwardStock.getModel(), tMallProductForwardStock.getGradeInfo(), tMallProductForwardStock.getMachineType(), tMallProductForwardStock.getBuyNumber(), tMallProductForwardStock.getGrade(), tMallProductForwardStock.getTwisting(), tMallProductForwardStock.getStatus(), tMallProductForwardStock.getCanBuyNumber(), tMallProductForwardStock.getBuyNumber(), tMallProductForwardStock.getSendNumber(), tMallProductForwardStock.getWaitOutNumber(), tMallProductForwardStock.getWaitInNumber(), tMallProductForwardStock.getStock(),
                                tMallProductForwardStock.getStockBoxNumber(), tMallProductForwardStock.getSortCode(), tMallProductForwardStock.getSortName());
                        mallProductForwardFormateVo.setPrice(new BigDecimal(0.0));
                        mallProductForwardFormateVo.setWeight(new BigDecimal(0.0));
                        mallProductForwardFormateVo.setColor(tMallProductForwardStock.getColor());
                        mallProductForwardFormateVo.setMachineNo(tMallProductForwardStock.getMachineNo());
                        //反了

                        for (MallOrderItemDetail mallOrderItemDetail : mallOrderItemDetailList) {


                            //2018/12/6现在不能确定唯一性
                            //如果订单产品属性被手动改变会有问题

                            //审核之前是库存列表，要匹配foward表
                            //审核后是产品列表，但是又能自己修改
                            String cmpStr = mallOrderItemDetail.getMaterialCode() + mallOrderItemDetail.getColor() + mallOrderItemDetail.getGrade() + mallOrderItemDetail.getTwisting();
                            if (materialCodeSet.contains(cmpStr)) {
                                continue;
                            }
                            boolean check = (mallOrderItemDetail.getMaterialCode().equals(tMallProductForwardStock.getMaterialCode()) && (mallOrderItemDetail.getInventoryOrganization().equals(tMallProductForwardStock.getInventoryOrganization()))
                                    && mallOrderItemDetail.getGrade().equals(tMallProductForwardStock.getGrade())
                                    && mallOrderItemDetail.getColor().equals(tMallProductForwardStock.getColor()) && mallOrderItemDetail.getTwisting().equals(tMallProductForwardStock.getTwisting()));

                            if (check) {
                                materialCodeSet.add(mallOrderItemDetail.getMaterialCode() + mallOrderItemDetail.getColor() + mallOrderItemDetail.getGrade() + mallOrderItemDetail.getTwisting());
                                mallProductForwardFormateVo.setPrice(mallOrderItemDetail.getCurrentUnitPrice());
                                mallProductForwardFormateVo.setWeight(mallOrderItemDetail.getQuantity());
                                mallProductForwardFormateVo.setRate(mallOrderItemDetail.getRate());
                                mallProductForwardFormateVo.setResidualQuantity(mallOrderItem.getResidualQuantity());
                                mallProductForwardFormateVo.setOrderItemId(mallOrderItem.getId());
                                mallProductForwardFormateVo.setExFactoryPrice(mallOrderItemDetail.getExFactoryPrice());
                                mallProductForwardFormateVo.setFreightPaymentType(mallOrderItemDetail.getFreightPaymentType());
                                mallProductForwardFormateVo.setSalesOrganization(mallOrderItemDetail.getSalesOrganization());
                                mallProductForwardFormateVo.setPaymentMethods(mallOrderItemDetail.getPaymentMethods());
                                mallProductForwardFormateVo.setSalesType(mallOrderItemDetail.getSalesType());
                                mallProductForwardFormateVo.setGroupNo(mallOrderItemDetail.getGroupNo());
                                mallProductForwardFormateVo.setCheckQuantity(mallOrderItemDetail.getCheckQuantity());
                                mallProductForwardFormateVo.setMachineNo(mallOrderItemDetail.getMachineNo());
                                mallProductForwardFormateVo.setGrade(mallOrderItemDetail.getGrade());
                                mallProductForwardFormateVo.setColor(mallOrderItemDetail.getColor());
                                mallProductForwardFormateVo.setTwisting(mallOrderItemDetail.getTwisting());

//                                    count++;
                                //未审核之前是库存列表
                                //审核之后是产品列表
                                count++;
                                break;
                            }
                        }

                        //保留原来的
                        //如果是审核之前的是库存列表之后是产品列表

                        //如果是审核之后如果count = 0那么不加
                        //如果是审核之前都加
                        boolean check = (mallOrder.getStatus() == 10) || (mallOrder.getStatus() != 10 && count != 0);
                        if (check) {
                            mallProductForwardStockList.add(mallProductForwardFormateVo);
                            //2018/11/23现在要拆分等级
                            List<MallProductForwardFormateVo> mallProductForwardFormateVoList = gradeMap.get(mallProductForwardFormateVo.getGrade());
                            if (mallProductForwardFormateVoList == null) {
                                mallProductForwardFormateVoList = new ArrayList<>();
                            }
                            mallProductForwardFormateVoList.add(mallProductForwardFormateVo);
                            gradeMap.put(mallProductForwardFormateVo.getGrade(), mallProductForwardFormateVoList);
                        }

                        orderItemVo.setMallProductForwardStockList(mallProductForwardStockList);

                        //得到所有的库存列表
                        MallProductForwardFormateVo subMallProductForwardStock = new MallProductForwardFormateVo(mallProductForwardFormateVo.getId(), mallProductForwardFormateVo.getInventoryOrganization(),
                                mallProductForwardFormateVo.getFactory(), mallProductForwardFormateVo.getMaterialCode(), mallProductForwardFormateVo.getMaterialName(), mallProductForwardFormateVo.getSpecifications(), mallProductForwardFormateVo.getModel(),
                                mallProductForwardFormateVo.getGradeInfo(), mallProductForwardFormateVo.getMachineType(), mallProductForwardFormateVo.getNetworkPly(), mallProductForwardFormateVo.getGrade(), mallProductForwardFormateVo.getTwisting(),
                                mallProductForwardFormateVo.getStatus(), mallProductForwardFormateVo.getCanBuyNumber(), mallProductForwardFormateVo.getBuyNumber(), mallProductForwardFormateVo.getSendNumber(), mallProductForwardFormateVo.getWaitOutNumber(),
                                mallProductForwardFormateVo.getWaitInNumber(), mallProductForwardFormateVo.getStock(), mallProductForwardFormateVo.getStockBoxNumber(), mallProductForwardFormateVo.getSortCode(), mallProductForwardFormateVo.getSortName(), mallProductForwardFormateVo.getPrice(),
                                mallProductForwardFormateVo.getWeight(), mallProductForwardFormateVo.getRate(), mallProductForwardFormateVo.getExFactoryPrice(), mallProductForwardFormateVo.getResidualQuantity(), mallProductForwardFormateVo.getSalesOrganization(),
                                mallProductForwardFormateVo.getSalesType(), mallProductForwardFormateVo.getFreightPaymentType(), mallProductForwardFormateVo.getPaymentMethods(), mallProductForwardFormateVo.getGroupNo());
                        subMallProductForwardStock.setCheckQuantity(mallProductForwardFormateVo.getCheckQuantity());
                        subMallProductForwardStock.setTwisting(mallProductForwardFormateVo.getTwisting());
                        subMallProductForwardStock.setColor(mallProductForwardFormateVo.getColor());
                        subMallProductForwardStock.setMachineNo(mallProductForwardFormateVo.getMachineNo());
                        subMallProductForwardStock.setGrade(mallProductForwardFormateVo.getGrade());
                        boolean checkSubOrder = mallOrderItemDetailList.size() == 0;
                        //如果是待审核状态,直接pass
                        //目前如果待审核就不会有子订单
                        if (mallOrder.getStatus() == 10) {
                            subMallProductForwardStock = null;
                        }

                        if (subMallProductForwardStock != null) {
                            //如果是审核状态并且存在子订单
                            if (mallOrder.getStatus() == 10 && !checkSubOrder) {
                                subMallProductForwardStockList.add(subMallProductForwardStock);
                            } else if (mallOrder.getStatus() != 10) {
                                //如果是审核通过状态
                                subMallProductForwardStockList.add(subMallProductForwardStock);
                            }
                        }
                    }

                    materialCodeSet.clear();


                    //把map封装成一个list
                    gradeMap.forEach((key, value) -> {
                        MallProductForwardWithGrade mallProductForwardWithGrade = new MallProductForwardWithGrade();
                        mallProductForwardWithGrade.setGrade(key);
                        mallProductForwardWithGrade.setMallProductForwardStockList(value);
                        mallProductForwardWithGradeList.add(mallProductForwardWithGrade);
                        gradeList.add(key);
                    });
                }

                orderItemVo.setGradeList(gradeList);
                orderItemVo.setMallProductForwardWithGradeList(mallProductForwardWithGradeList);
            }
                //如果是子订单详情
                if (groupNo != null && orderItemVo.getMallProductForwardStockList().size() != 0 && orderItemVo.getMallProductForwardStockList().get(0).getGroupNo().equals(groupNo)) {
                    orderItemVoList.add(orderItemVo);
                } else if (groupNo == null) {
                    orderItemVoList.add(orderItemVo);
                }
            }

                orderVo.setTotalPrice(totalPrice);
                orderVo.setPayment(totalPrice);
                orderVo.setOrderItemVoList(orderItemVoList);



            //得到完所有的库存列表之后封装到一个orderItemVo里面
            //得到上一级的属性
            List<OrderItemDetialVo> orderItemDetailVoList = new ArrayList<>();
            for (MallProductForwardFormateVo mallProductForwardFormateVo : subMallProductForwardStockList) {
                OrderItemDetialVo orderItemDetailVo = new OrderItemDetialVo();
                //原先是根据订单order_item_id得到产品的属性去匹配库存信息
                //现在根据库存信息-->order_item_id-->产品信息   但是这个库存没有order_item_id 导致错误
                //要根据库存信息去匹配产品信息
                if (mallProductForwardFormateVo.getOrderItemId() == null) {
                    orderItemDetailVo.setMallProductForwardStock(mallProductForwardFormateVo);
                    orderItemDetailVo.setGrade(mallProductForwardFormateVo.getGrade());
                    orderItemDetailVo.setModel(mallProductForwardFormateVo.getModel());
                    orderItemDetailVo.setName(mallProductForwardFormateVo.getMaterialName());
                    orderItemDetailVo.setPrice(mallProductForwardFormateVo.getPrice());
                    orderItemDetailVoList.add(orderItemDetailVo);
                    continue;
                }
                MallOrderItem mallOrderItem = mallOrderItemMapper.selectByPrimaryKey(mallProductForwardFormateVo.getOrderItemId());
                orderItemDetailVo.setGrade(mallOrderItem.getGrade());
                String sImgUrl = mallOrderItem.getProductImage();
                if (sImgUrl.contains(",")) {
                    sImgUrl = sImgUrl.split(",")[0];
                }
                orderItemDetailVo.setImg(sImgUrl);
                orderItemDetailVo.setProductId(mallOrderItem.getProductId());
                orderItemDetailVo.setModel(mallOrderItem.getProductName().split(",", -1)[2]);
                orderItemDetailVo.setPrice(mallOrderItem.getTotalPrice());
                orderItemDetailVo.setUnitPrice(mallOrderItem.getCurrentUnitPrice());

                orderItemDetailVo.setName(mallOrderItem.getProductName());
                orderItemDetailVo.setWeight(mallOrderItem.getQuantity());
                orderItemDetailVo.setOrderItemId(mallOrderItem.getId());
                orderItemDetailVo.setColor(mallOrderItem.getProductName().split(",", -1)[7]);
                orderItemDetailVo.setResidualQuantity(mallOrderItem.getResidualQuantity());
                orderItemDetailVo.setMallProductForwardStock(mallProductForwardFormateVo);
                orderItemDetailVoList.add(orderItemDetailVo);
            }


            //进行分组
            for (OrderItemDetialVo orderItemDetailVo : orderItemDetailVoList) {
                List<OrderItemDetialVo> subOrderItemDetialVoList = map.get(orderItemDetailVo.getMallProductForwardStock().getGroupNo());
                if (subOrderItemDetialVoList == null) {
                    subOrderItemDetialVoList = new ArrayList<>();
                }
                subOrderItemDetialVoList.add(orderItemDetailVo);
                map.put(orderItemDetailVo.getMallProductForwardStock().getGroupNo(), subOrderItemDetialVoList);
            }

            for (Map.Entry<Long, List<OrderItemDetialVo>> entry : map.entrySet()) {
                MallProductForwardFormateParentVo mallProductForwardFormateParentVo = new MallProductForwardFormateParentVo();
                mallProductForwardFormateParentVo.setGroupNo(entry.getKey());
                mallProductForwardFormateParentVo.setOrderItemDetialVoList(entry.getValue());
                if (entry.getKey() == null) {
                    continue;
                }
                mallProductForwardFormateParentVoList.add(mallProductForwardFormateParentVo);
            }


        orderVo.setOrderItemVoList(orderItemVoList);

        orderVo.setOrderItemDetialVoList(orderItemDetailVoList);
        orderVo.setMallProductForwardFormateParentVoList(mallProductForwardFormateParentVoList);

        return orderVo;
    }



    /**
     * @Date 2018/11/20 13:43
     * @Param [userId, subOrderJsonStr, opinion]
     * @return com.hmall.common.ServerResponse
     * @Description
     */
    public ServerResponse createSubOrder(Integer userId, Long orderNo, String subOrderJsonStr) {


        Gson gson = new Gson();
        List<MaterialGrandVo> materialGrandVoList = gson.fromJson(subOrderJsonStr, new TypeToken<List<MaterialGrandVo>>() {}.getType());

//        //先把原来的重量和价格重置
//        for(MaterialGrandVo materialGrandVo : materialGrandVoList) {
//            List<MaterialParentVo> materialParentVoList = materialGrandVo.getMaterialParentVoList();
//            for(MaterialParentVo materialParentVo : materialParentVoList){
//                int itemId = materialParentVo.get
//            }
//
//        }

        //将全部清零
        mallOrderMapper.updatePaymentWithOrderNo(orderNo, new BigDecimal(0.0));
        mallOrderItemMapper.updateQuantity(orderNo, new BigDecimal(0.0));
        mallOrderItemMapper.updateTotalPrice(orderNo, new BigDecimal(0.0));


        BigDecimal price = new BigDecimal(0.0);
        for(MaterialGrandVo materialGrandVo : materialGrandVoList) {
            MallOrder mallOrder = mallOrderMapper.selectAllByOrderNo(orderNo);
            Long groupNo = NumberUtil.createGroupNo(mallOrder.getDealerId());

            MallOrderRemark mallOrderRemark = new MallOrderRemark();
            mallOrderRemark.setContent(materialGrandVo.getOpinion());
            mallOrderRemark.setOrderNo(groupNo);
            mallOrderRemark.setUserId(userId);
            mallOrderRemark.setType(1);
            mallOrderRemark.setCreateTime(new Date());
            mallOrderRemarkMapper.insert(mallOrderRemark);

            price = price.add(insertOrderItemDetail(materialGrandVo.getMaterialParentVoList(), orderNo, mallOrder.getUserId(), groupNo, materialGrandVo.getOpinion(), mallOrder.getId()));
        }
        //更新价格
        mallOrderMapper.updatePaymentWithOrderNo(orderNo, price);

        return ServerResponse.createBySuccess();
    }


    /**
     * @Date 2018/11/8 14:48
     * @Param [userId, orderNo, jsonOrderItemStr, opinion, status]
     * @return com.hmall.common.ServerResponse
     * @Description // 业务员审核订单
     */
    public ServerResponse changeOrderStatus(Integer userId, Long orderNo, String opinion, Integer status) throws InterruptedException {


//        String testStr = "[{\"productId\":518,\"grade\":\"AA3不定重\",\"price\":20,\"weight\":42}]";
//        String testStr1 = "[{\"planItemId\":138,\"grade\":\"AA3\",\"productId\":685,\"weight\":45}]";

        //新json grade productId materialVoList(price, materialCode, weight)
//        String testStr = "[{\"grade\":\"AA3不定重\", \"productId\":518,\"materialVoList\":[{\"price\":100,\"materialCode\":\"DSADDDA\",\"weight\":100}]}]";
//        String testStr =
//                "[{\"materialVoList\":[{\"price\":\"12\",\"weight\":\"25\",\"materialCode\":\"XAS11196S11C00L2\"}]," + "\"grade\":\"A\",\"productId\":\"4329\"}]";
////

//        String testStr = "[{\"grade\":\"AA\",\"productId\":\"4845\",\"materialVoList\":[{\"exFactoryPrice\":\"21\",\"weight\":10,\"price\":\"21.00\",\"materialCode\":\"FJR01703911C00E1J\",\"rate\":\"16\"}]}]";
//        jsonOrderItemStr = testStr;
        //如果审核过 不能再审核
        //2018/9/29 改为原子性
        MallOrder preMallOrder = mallOrderMapper.selectAllByOrderNo(orderNo);
        if(null != preMallOrder && (!Const.ORDER_WAIT_EXAM .equals(preMallOrder.getStatus()))) {
            return ServerResponse.createByErrorMessage("该订单已经被审核过");
        }

        //更改库存
        String params1 = "";
        String params2 = "2";
        List<MallOrderItem> list = mallOrderItemMapper.getByOrderNo(orderNo);
        for (MallOrderItem aList : list) {
            List<MallOrderItemDetail> list1 = mallOrderItemDetailMapper.selectByItemId(aList.getId());
            if (list1.size() == 0) {
                return ServerResponse.createByErrorMessage(aList.getProductModel() + "产品未选择物料编码");
            }
            for (MallOrderItemDetail mallOrderItemDetail : list1){
                params1 = params1 + mallOrderItemDetail.getMaterialCode() + "-" + mallOrderItemDetail.getGrade()
                        + "-" + mallOrderItemDetail.getTwisting() + "-" + mallOrderItemDetail.getColor() + "-" + mallOrderItemDetail.getMachineNo() + "-" + mallOrderItemDetail.getCheckQuantity().intValue() + ",";
            }
        }
        params1 = params1.substring(0,params1.length()-1);
        Map map2 = new HashMap();
        map2.put("itemList",params1);
        map2.put("type",params2);
        SysUser testUser = userMapper.selectSalesmanByUserId(preMallOrder.getUserId());
        map2.put("deptId",testUser.getDeptId().toString());
        Diction diction = dictionMapper.selectByDictionKey("wmsSwitch");
        if (diction!=null&&diction.getValue().equals("1")){
            String s = HttpClientUtil.doPostWithParam("http://47.98.171.71:9600/wms/inventorys/batch/updateInventory",map2);
            Gson gson = new Gson();
            Map map3 = new HashMap();
            map3 = gson.fromJson(s, map3.getClass());
            if (!map3.get("code").toString().equals("200.0")){
                return ServerResponse.createByErrorMessage(map3.get("data").toString());
            }
        }

        mallOrderMapper.updateStatus2(0, orderNo);
        mallOrderMapper.updateStatus3(0, orderNo);


        MallOrder mallOrder = mallOrderMapper.selectAllByOrderNo(orderNo);
        int dbStatus;

//        Map<String, Class<MaterialVo>> map = new HashMap<>(16);
//        map.put("materialVoList", MaterialVo.class);
//
//        List<MaterialParentVo> materialParentVoList = JsonUtils.jsonToList(jsonOrderItemStr, MaterialParentVo.class, map);
        //审核通过改变产品
        //审核不通过不改变产品
        if (status == 1) {


            //审核通过 都要重跟单员和财务的状态
            mallOrderMapper.updateStatus1(1, orderNo);
            mallOrderMapper.updateStatus3(1, orderNo);
            //json转换


            //2018/10/16 修改为跟单员审核通过之后订单才改为待发货
//            //更改订单状态为待发货
//            dbStatus = 20;
//
//            mallOrderMapper.updateByOrderNo(dbStatus, orderNo);

            //删除原来的所有的orderItem
//            mallOrderItemMapper.deleteByOrderNo(orderNo);

//            insertOrderItemDetail(materialParentVoList, orderNo, userId, , , )

            //更新2018/11/13所需要的额外信息
            // mallOrderMapper.updateOtherArgs(salesOrganization, salesType, freightPaymentType, paymentMethods, orderNo);
            //2018/11/20改了

              //2018/10/31
            //现在业务员审核通过需要给资金和跟单发推送
            try {
                jpushController.backPushMessage(userId, 9, orderNo.toString());
            } catch (IOException e) {
                return ServerResponse.createByErrorMessage("给跟单和资金发推送失败");
            } catch (ParseException e) {
                e.printStackTrace();
            }

            return ServerResponse.createBySuccess("审核完成");
        } else if(status == 2){

            dbStatus = 0;
            mallOrderMapper.updateStatus1(2, orderNo);

            mallOrderMapper.updateByOrderNo(dbStatus, orderNo);

            String title = "【华鼎云商城】订单不审核通过";
            if(opinion == null || "".equals(opinion)){
                opinion = "无备注信息";
            }
            String body = "您好，您的采购订单" + orderNo + "未通过商城审核，请重新进行下单" + "备注信息：" + opinion;
            String userName = userMapper.selectByPrimaryKey(mallOrder.getUserId()).getUsername();
            String type = "order_status";
            String value = mallOrder.getOrderNo().toString();
            try {
                jpushController.jPushMethod(title, body, userName, type, value);
            } catch (IOException e) {
                e.printStackTrace();
            }

            Map<String, String> msgMap = new HashMap<>(16);
            msgMap.put("mobile", userName);
            msgMap.put("orderNo", orderNo.toString());
            msgMap.put("text", title);
            EnvUtil envUtil = new EnvUtil();
            String url = envUtil.getPreUrl("hCloud");
            HttpClientUtil.doGetWithParam(url + "/admin/orderMsg", msgMap);

            return ServerResponse.createBySuccess("订单审核拒绝成功");
        }else if(status == 3){

            mallOrderMapper.updateStatus2(1, orderNo);
//            BigDecimal price = merchandiserService.updateOrder(orderNo, mallOrder.getUserId(), materialParentVoList);
//            insertOrderItemDetail(, , , , , )
            BigDecimal price = mallOrder.getPayment();


            //若果没有与orderItemDetail匹配的orderItem要把orderItem删除
            List<MallOrderItem> mallOrderItemList = mallOrderItemMapper.selectAllByOrderNo(orderNo);
            BigDecimal totalPrice = new BigDecimal(0.0);
            for(MallOrderItem mallOrderItem : mallOrderItemList){
                int count = mallOrderItemDetailMapper.selectCountByOrderItemId(mallOrderItem.getId());
                if(count == 0){
                    mallOrderItemMapper.deleteByOrderItemId(mallOrderItem.getId());
                }else{
                    totalPrice = totalPrice.add(mallOrderItem.getTotalPrice());
                }

            }

            //更新mallOrder 下的payment

            mallOrderMapper.updatePaymentWithOrderNo(orderNo, totalPrice);

            merchandiserService.merchPassExam(orderNo, null, mallOrder.getUserId(), opinion, totalPrice);

            return ServerResponse.createBySuccess("业务员直接审核通过成功");
        }
            return ServerResponse.createBySuccess();
    }

    private BigDecimal insertOrderItemDetail(List<MaterialParentVo> materialParentVoList, Long orderNo, Integer userId, Long groupNo, String opinion, Integer orderId){
//        BigDecimal price = mallOrderMapper.selectByOrderNo(orderNo).getPayment();
        BigDecimal price = new BigDecimal(0.0);
        //如果没有创建过子订单 price置为0
        List<MallOrderItemDetail> mallOrderItemDetailList = mallOrderItemDetailMapper.selectCheck(orderNo);
//        if(mallOrderItemDetailList == null) {
//            price = new BigDecimal(0.0);
//        }
//        BigDecimal price = new BigDecimal(0.0);


        for (MaterialParentVo materialParentVo : materialParentVoList) {
            MallOrderItem mallOrderItem = new MallOrderItem();
            mallOrderItem.setUserId(userId);
            mallOrderItem.setOrderNo(orderNo);
            mallOrderItem.setProductId(materialParentVo.getProductId());
            MallProduct mallProduct = mallProductMapper.selectByProductId(materialParentVo.getProductId());
            mallOrderItem.setProductName(mallProduct.getName());
            mallOrderItem.setProductImage(mallProduct.getMainImage());
            mallOrderItem.setCreateTime(new Date());
            mallOrderItem.setGrade(materialParentVo.getGrade());
            mallOrderItem.setCommentCheck(0);
            String[] nameStr = mallProduct.getName().split(",", -1);
            mallOrderItem.setProductModel(nameStr[2]);
            mallOrderItem.setCurrentUnitPrice(new BigDecimal(0.0));
            mallOrderItem.setResidualQuantity(new BigDecimal(0.0));
            mallOrderItem.setQuantity(new BigDecimal(0.0));
            mallOrderItem.setTotalPrice(new BigDecimal(0.0));

            //先处理productItemDetial表
            List<MaterialVo> materialVoList = materialParentVo.getMaterialVoList();
            //有物料编码，等级，重量
            //去查库存表

            //2018/11/21 现在有子订单不能直接删除如果productId和grade一样要进行更新
            MallOrderItem oldMallOrderItem = mallOrderItemMapper.selectByOrderNoAndGradeAndProductId(orderNo, materialParentVo.getGrade(), materialParentVo.getProductId());
            if (oldMallOrderItem == null) {
                //先插入 找出itemId
                //用insert弊端 不会插入默认值 导致下面有sql报错，价格一栏变成Null
                mallOrderItemMapper.insert(mallOrderItem);
            }

            //如果原来有
            Integer itemId = mallOrderItemMapper.selectByProductIdAndGradeAndOrderNo(orderNo, materialParentVo.getProductId(), materialParentVo.getGrade());
            MallOrderItem nowMallOrderItem = mallOrderItemMapper.selectByOrderItemId(itemId);

            BigDecimal orderItemQuantity = nowMallOrderItem.getQuantity();
            BigDecimal orderItemPrice = nowMallOrderItem.getTotalPrice();
            BigDecimal orderItemUnitPrice;
            //需要更新orderItem表的数据...
            //totalPrice quantity residualQuantity
            for (MaterialVo materialVo : materialVoList) {
                //得到物料编码
                String materialCode = materialVo.getMaterialCode();
                MallOrderItemDetail mallOrderItemDetail = new MallOrderItemDetail();
                mallOrderItemDetail.setCurrentUnitPrice(materialVo.getPrice());
                mallOrderItemDetail.setInventoryOrganization(materialVo.getInventoryOrganization());
                mallOrderItemDetail.setMaterialCode(materialCode);
                mallOrderItemDetail.setOrderItemId(itemId);
                mallOrderItemDetail.setQuantity(materialVo.getWeight());
                mallOrderItemDetail.setResidualQuantity(materialVo.getCheckQuantity());
                mallOrderItemDetail.setTotalPrice(materialVo.getCheckQuantity().multiply(materialVo.getPrice()));
                mallOrderItemDetail.setExFactoryPrice(materialVo.getExFactoryPrice());
                mallOrderItemDetail.setRate(materialVo.getRate());
                mallOrderItemDetail.setCheckQuantity(materialVo.getCheckQuantity());
                mallOrderItemDetail.setGrade(materialVo.getGrade());
                mallOrderItemDetail.setTwisting(materialVo.getTwisting());
                mallOrderItemDetail.setMachineNo(materialVo.getMachineNo());
                mallOrderItemDetail.setColor(materialVo.getColor());


                orderItemPrice = orderItemPrice.add(mallOrderItemDetail.getTotalPrice());
                orderItemQuantity = orderItemQuantity.add(mallOrderItemDetail.getCheckQuantity());
                mallOrderItemDetail.setCreateTime(new Date());
                //2018/11/20
                mallOrderItemDetail.setSalesOrganization(materialVo.getSalesOrganization());
                mallOrderItemDetail.setFreightPaymentType(materialVo.getFreightPaymentType());
                mallOrderItemDetail.setPaymentMethods(materialVo.getPaymentMethods());
                mallOrderItemDetail.setSalesType(materialVo.getSalesType());
                mallOrderItemDetail.setGroupNo(groupNo);
                mallOrderItemDetailMapper.insert(mallOrderItemDetail);
            }
            price = price.add(orderItemPrice);
            orderItemUnitPrice = orderItemPrice.divide(orderItemQuantity, 2);
            //上面有报错有可能导致没有价格
            log.info("开始更新价格");
            mallOrderItemMapper.updatePriceAndTwoQuantity(itemId, orderItemUnitPrice, orderItemPrice, orderItemQuantity);
        }
            //插入
            log.info("订单详情插入成功");

         //   mallOrderMapper.updatePaymentWithOrderNo(orderNo, price);

            //更新payment
//            mallOrderMapper.myUpdatePayment(orderId, price);
        return price;
    }

    /**
     * @Date 2018/11/8 14:54
     * @Param [userId, customerUserId, status, pageNum, pageSize]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo>
     * @Description // 1:全部 2：审核中 3：审核通过 4：审核驳回 6：新建计划 7.待审核
     */
    public ServerResponse<PageVo<BackPlanVo>> listPlanList(Integer userId, Integer customerUserId, Integer status, Integer pageNum, Integer pageSize) {

        if (status == null || status < 1 || status > 7) {
            return ServerResponse.createByErrorMessage("请输入正确的状态");
        }

        //1.先根据用户查看拥有什么权限
        List<String> menuList = menuMapper.listMenuByUserId(userId);
        int role = DealerMenuUtil.getBackRole(menuList);

        int planDBStatus = getPlanDBStatus(status);

        List<Integer> salesmanIdList = new ArrayList<>();
        if (role == 0) {
            //办事员
            salesmanIdList.add(userId);
        } else {
            salesmanIdList = getSalesmanIdList(userMapper.selectByPrimaryKey(userId).getDeptId());
        }

        //默认创建人是该公司的最早注册的人
        Integer createCustomerUserId = -1;
        if (customerUserId != null) {
            Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(customerUserId);
            if (customerId == null) {
                return ServerResponse.createByErrorMessage("该用户暂未绑定公司");
            }
            createCustomerUserId = customerMapper.selectCustomerUserId(customerId);
            if (createCustomerUserId == null) {
                return ServerResponse.createByErrorMessage("该公司暂未绑定业务员");
            }
        }
        List<MallProductPlan> mallProductPlanList = mallProductPlanMapper.selectByCustomerUserIdWithStatus(salesmanIdList, createCustomerUserId, planDBStatus);
        //要进行一轮筛选
        //如果是6选出空白的否则必须是有没有计划详情的
        //只是当月份

        //如果不是是历史

        Calendar calendar = Calendar.getInstance();

        List<BackPlanVo> backPlanVoList = new ArrayList<>();
        for (MallProductPlan mallProductPlan : mallProductPlanList) {
            int count = mallProductPlanItemMapper.selectCountByProductPlanNo(mallProductPlan.getPlanNo());
            //20180919031887701 824
            //待审核的状态
            calendar.setTime(mallProductPlan.getCreateTime());
            if (status == 6) {
                //如果不是空的直接没有
                if (count != 0) {
                    continue;
                }
                //如果不是当前月份的也没有
                Integer createYear = calendar.get(Calendar.YEAR);
                Integer createMonth = calendar.get(Calendar.MONTH) + 1;
                Calendar cal1 = Calendar.getInstance();
                Integer nowYear = cal1.get(Calendar.YEAR);
                Integer nowMonth = cal1.get(Calendar.MONTH) + 1;
                if ((!createYear.equals(nowYear)) || (!createMonth.equals(nowMonth))) {
                    continue;
                }
            } else {
                if (count == 0) {
                    continue;
                }
                //对于有计划的东西办事处不显示待审核的订单

                //2018.9.11改为也业务员也能看见待审核的计划
                //if(mallProductPlan.getStatus() == 0) continue;
            }


            Integer planMonth = calendar.get(Calendar.MONTH);

            int tCustomerUserId = mallProductPlan.getUserId();
            BackPlanVo backPlanVo = new BackPlanVo();
            int tCustomerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(tCustomerUserId);
            backPlanVo.setCustomerId(tCustomerId);
            backPlanVo.setCustomerName(customerMapper.selectByPrimaryKey(tCustomerId).getBusName());

            backPlanVo.setCustomerUserId(tCustomerUserId);
            backPlanVo.setCustomerUserName(userMapper.selectByPrimaryKey(tCustomerUserId).getRealName());
            backPlanVo.setPlanNo(mallProductPlan.getPlanNo());

            calendar.setTime(mallProductPlan.getCreateTime());
            String createTime = "";
            int flag = 0;
            Integer realPlanMonth = planMonth + 1;
            if(13 == realPlanMonth) {
                flag = 1;
            }
            createTime += (calendar.get(Calendar.YEAR) + flag)+ ".";


            if (realPlanMonth <= 9) {
                createTime += "0" + realPlanMonth;
            } else {
                if(13 == realPlanMonth) {
                    realPlanMonth = 1;
                }
                createTime += realPlanMonth;

            }

            backPlanVo.setPlanTime(createTime);
            backPlanVo.setStatus(mallProductPlan.getStatus());
            backPlanVo.setSubmitPerson(mallProductPlan.getSubmitPerson());
            backPlanVoList.add(backPlanVo);
        }

        int total = backPlanVoList.size();
        int pageStart = pageSize * (pageNum - 1);
        int pageEnd = Math.min(total, pageStart + pageSize);
        List<BackPlanVo> subBackPlanVoList = backPlanVoList.subList(pageStart, pageEnd);
        PageVo<BackPlanVo> pageVo = new PageVo<>(pageNum, pageSize, total, subBackPlanVoList);
        return ServerResponse.createBySuccess(pageVo);
    }

    /**
     * @Date 2018/11/8 14:55
     * @Param [planNo]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.BackPlanDetial>
     * @Description // 得到计划详情
     */
    public ServerResponse<BackPlanDetial> getPlanDetail(Long planNo) {

        BackPlanDetial backPlanDetial = new BackPlanDetial();
        MallProductPlan mallProductPlan = mallProductPlanMapper.selectByPlanNo(planNo);
        int status = mallProductPlan.getStatus();
        //如果状态为待审核
        //待审核看不见评价 ?..default 有数据，要加自己加
//        if (status != 1) {
        //现在都能看见
        backPlanDetial.setRemark(mallProductPlan.getRemark());
//        }

        List<MallProductPlanItem> mallProductPlanItemList = mallProductPlanItemMapper.listProductPlanItemByPlanNo(planNo);

        List<BackPlanItemVo> backPlanItemVoList = new ArrayList<>();
        for (MallProductPlanItem mallProductPlanItem : mallProductPlanItemList) {

            Integer productId = mallProductPlanItem.getProductId();
            BackPlanItemVo backPlanItemVo = new BackPlanItemVo();
            String name = mallProductMapper.selectByPrimaryKey(productId).getName();
            String []nameStr = name.split(",",-1);
            backPlanItemVo.setProductId(productId);
            backPlanItemVo.setType(nameStr[0]);
            backPlanItemVo.setGloss(nameStr[1]);
            backPlanItemVo.setModel(nameStr[2]);
            backPlanItemVo.setFineAndPore(nameStr[3] + nameStr[4]);
            backPlanItemVo.setSingleShare(nameStr[5]);
            backPlanItemVo.setColor(nameStr[6]);
            backPlanItemVo.setSection(nameStr[7]);
            backPlanItemVo.setNetwork(nameStr[8]);
            backPlanItemVo.setTwisting(nameStr[9]);
            backPlanItemVo.setGrade(mallProductPlanItem.getGrade());
            backPlanItemVo.setWeight(mallProductPlanItem.getAmount());
            backPlanItemVo.setPlanItemId(mallProductPlanItem.getPlanItemId());

            backPlanItemVoList.add(backPlanItemVo);
        }

        backPlanDetial.setBackPlanItemVo(backPlanItemVoList);
        backPlanDetial.setStatus(status);
        backPlanDetial.setPlanNo(planNo);
        backPlanDetial.setCustomerUserId(mallProductPlan.getUserId());
        backPlanDetial.setCreateTime(mallProductPlan.getCreateTime());
        backPlanDetial.setUsername(userMapper.selectByPrimaryKey(mallProductPlan.getUserId()).getUsername());
        backPlanDetial.setCustomerName(customerMapper.selectByUserId(mallProductPlan.getUserId()).getBusName());
        return ServerResponse.createBySuccess(backPlanDetial);
    }


    public ServerResponse<PageVo<CustomerVo>> listCustomer(Integer userId, Integer pageNum, Integer pageSize) {

        List<CustomerVo> customerVoList = new ArrayList<>();
        List<String> menuList = menuMapper.listMenuByUserId(userId);
        int role = DealerMenuUtil.getBackRole(menuList);
        if (role == 0) {

            List<Integer> customerIdList = getCustomerIdList(userId);
            for (Integer customerId : customerIdList) {
                SysCustomer customer = customerMapper.selectByPrimaryKey(customerId);
                customerVoList.add(new CustomerVo(customerId, customer.getBusName(), customer.getBusAddress()));
            }

        } else {
            //客户全列表
            //1.根据办事员的user找到他所在的办事处
            Integer deptId = userMapper.selectByPrimaryKey(userId).getDeptId();

            //2.先找出所有的业务员（包括自己的列表）
            //暂时不存在一个公司绑定两个业务员的情况
            List<Integer> salesmanIdList = userMapper.selectUserIdListByDeptId(deptId);
            for (Integer salesmanId : salesmanIdList) {
                List<Integer> customerIdList = getCustomerIdList(salesmanId);
                for (Integer customerId : customerIdList) {
                    SysCustomer customer = customerMapper.selectByPrimaryKey(customerId);
                    customerVoList.add(new CustomerVo(customerId, customer.getBusName(), customer.getBusAddress()));
                }
            }
        }

        int total = customerVoList.size();
        int pageStart = pageSize * (pageNum - 1);
        int pageEnd = Math.min(total, pageStart + pageSize);
        List<CustomerVo> subCustomerVoList = customerVoList.subList(pageStart, pageEnd);
        PageVo<CustomerVo> pageVo = new PageVo<>(pageNum, pageSize, total, subCustomerVoList);
        return ServerResponse.createBySuccess(pageVo);
    }


    public ServerResponse<String> createRemark(String oldPlanListStr, String newPlanListStr) {

        StringBuilder remark = new StringBuilder();

//        String testStr = "[{\"planItemId\":138,\"grade\":\"AA3\",\"productId\":685,\"weight\":42}]";
//        String testStr1 = "[{\"planItemId\":138,\"grade\":\"AA3\",\"productId\":685,\"weight\":45}]";
//        oldPlanListStr = testStr;
//        newPlanListStr = testStr1;

        //旧的
        List<BackPlanItemSimpleVo> oldBackPlanItemSimpleVoList = JsonUtils.jsonToList(oldPlanListStr, BackPlanItemSimpleVo.class);

        long planNo = mallProductPlanItemMapper.selectByPrimaryKey(oldBackPlanItemSimpleVoList.get(0).getPlanItemId()).getPlanNo();

        //新的
        List<BackPlanItemSimpleVo> newBackPlanItemSimpleVoList = JsonUtils.jsonToList(newPlanListStr, BackPlanItemSimpleVo.class);

        //先少的产品
        //new产品必有old数目，防止越界
        for (int i = 0; i < oldBackPlanItemSimpleVoList.size(); i++) {

            BackPlanItemSimpleVo newBackPlanItemSimpleVo = newBackPlanItemSimpleVoList.get(i);
            BackPlanItemSimpleVo oldBackPlanItemSimpleVo = oldBackPlanItemSimpleVoList.get(i);

            if (newBackPlanItemSimpleVoList.get(i).getProductId() == 0) {
                //删除

                mallProductPlanItemMapper.deleteByPrimaryKey(newBackPlanItemSimpleVoList.get(i).getPlanItemId());
                String name = mallProductMapper.selectByPrimaryKey(newBackPlanItemSimpleVo.getPlanItemId()).getName();
                String model = name.split(",", -1)[2];
                String grade = newBackPlanItemSimpleVo.getGrade();
                remark.append("批号为：").append(model).append(" 等级为：").append(grade).append(" 的产品已被去除");
                continue;
            }

            if (!newBackPlanItemSimpleVo.equals(oldBackPlanItemSimpleVo)) {
                String oldName = mallProductMapper.selectByPrimaryKey(oldBackPlanItemSimpleVo.getProductId()).getName();
                String oldModel = oldName.split(",")[2];
                String oldGrade = oldBackPlanItemSimpleVo.getGrade();
                BigDecimal oldWeight = oldBackPlanItemSimpleVo.getWeight();
                remark.append("批号为：").append(oldModel).append(" 等级为：").append(oldGrade).append("重量为：").append(oldWeight).append("的产品");


                String newName = mallProductMapper.selectByPrimaryKey(newBackPlanItemSimpleVo.getProductId()).getName();
                String newModel = newName.split(",")[2];
                String newGrade = newBackPlanItemSimpleVo.getGrade();
                BigDecimal newWeight = newBackPlanItemSimpleVo.getWeight();
                remark.append("更改为" + "批号为：").append(newModel).append(" 等级为：").append(newGrade).append("重量为：").append(newWeight).append("的产品");

            }

            mallProductPlanItemMapper.updateByTreeAttr(oldBackPlanItemSimpleVo.getPlanItemId(), newBackPlanItemSimpleVo.getProductId(),
                    newBackPlanItemSimpleVo.getGrade(), newBackPlanItemSimpleVo.getWeight());
        }

        //然后进行插入

        for (int i = oldBackPlanItemSimpleVoList.size(); i < newBackPlanItemSimpleVoList.size(); i++) {
            BackPlanItemSimpleVo newBackPlanItemSimpleVo = newBackPlanItemSimpleVoList.get(i);
            String newName = mallProductMapper.selectByPrimaryKey(newBackPlanItemSimpleVo.getProductId()).getName();
            String newModel = newName.split(",")[2];
            String newGrade = newBackPlanItemSimpleVo.getGrade();
            BigDecimal newWeight = newBackPlanItemSimpleVo.getWeight();
            remark.append("新增了" + "批号为：").append(newModel).append(" 等级为：").append(newGrade).append("重量为：").append(newWeight).append("的产品");

            MallProductPlanItem mallProductPlanItem = new MallProductPlanItem(newBackPlanItemSimpleVo.getPlanItemId(), planNo, newBackPlanItemSimpleVo.getProductId(), newBackPlanItemSimpleVo.getGrade(), newBackPlanItemSimpleVo.getWeight());
            mallProductPlanItemMapper.insert(mallProductPlanItem);
        }

        return ServerResponse.createBySuccess(remark.toString());
    }


    /**
     * @Date 2018/11/8 14:57
     * @Param [planNo, jsonPlanItemStr, opinion, status]
     * @return com.hmall.common.ServerResponse
     * @Description //  3是保存 审核计划
     */
    public ServerResponse changePlanStatus(Long planNo, String jsonPlanItemStr, String opinion, Integer status) {

        int dbStatus;

        //如果审核通过
        if (Const.PLAN_PASS.equals(status) || Const.PLAN_SAVE.equals(status)) {
            //暂时不经过工作流
            if(Const.PLAN_PASS.equals(status)) {

                //计划状态 2是同意 1是审核中
                dbStatus = 2;
            }
            else {
                dbStatus = 1;
            }
            //json转换
            List<BackExamPlanItemVo> backExamPlanItemVoList = JsonUtils.jsonToList(jsonPlanItemStr, BackExamPlanItemVo.class);

            mallProductPlanMapper.updatePlanByPlanNoAndStatusWithOpinion(planNo, opinion, dbStatus);

            //更新子
            //先删除
            mallProductPlanItemMapper.deleteByPlanNo(planNo);

            for (BackExamPlanItemVo backExamPlanItemVo : backExamPlanItemVoList) {
                MallProductPlanItem mallProductPlanItem = new MallProductPlanItem();
                mallProductPlanItem.setAmount(backExamPlanItemVo.getWeight());
                mallProductPlanItem.setGrade(backExamPlanItemVo.getGrade());
                mallProductPlanItem.setPlanNo(planNo);
                mallProductPlanItem.setProductId(backExamPlanItemVo.getProductId());
                mallProductPlanItem.setResidualQuantity(backExamPlanItemVo.getWeight());
                mallProductPlanItemMapper.insert(mallProductPlanItem);
            }

        } else if (Const.PLAN_UNPASS.equals(status)){
            //变成失效
            dbStatus = 3;
            mallProductPlanMapper.updatePlanByPlanNoAndStatusWithOpinion(planNo, opinion, dbStatus);
        } else {
            return ServerResponse.createByErrorMessage("请输入正确的状态");
        }

        return ServerResponse.createBySuccess();
    }


    /**
     * @Date 2018/11/2 10:17
     * @Param [productListStr, opinion, customerUserId, shippingId, distCode, transportId]
     * @return com.hmall.common.ServerResponse
     * @Description // 业务员帮用户创建订单
     */
    public ServerResponse createOrder(String productListStr, String opinion, Integer customerUserId, Integer shippingId, Integer distCode, Integer transportId) {

        if (null == distCode) {
            return ServerResponse.createByErrorMessage("请输入正确的配送方式");
        }
        if (null == shippingId) {
            return ServerResponse.createByErrorMessage("请输入正确的收货地址");
        }

//           String testStr = "[{\"productId\":518,\"grade\":\"AA不定重\",\"price\":100,\"weight\":42}]";
//           productListStr = testStr;

        List<BackOrderItemVo> backOrderItemVoList = JsonUtils.jsonToList(productListStr, BackOrderItemVo.class);

        //创建订单
        Integer dealerId = sysDeptCustomerMapper.selectDealerIdByUserId(customerUserId);
        Long orderNo = NumberUtil.createOrderNo(dealerId);

        BigDecimal allPrice = new BigDecimal(0.0);
        for (BackOrderItemVo backOrderItemVo : backOrderItemVoList) {
            //先插入子
            MallOrderItem mallOrderItem = new MallOrderItem();
            mallOrderItem.setCommentCheck(0);
            mallOrderItem.setCreateTime(new Date());
            mallOrderItem.setCurrentUnitPrice(backOrderItemVo.getPrice());
            mallOrderItem.setGrade(backOrderItemVo.getGrade());
            mallOrderItem.setOrderNo(orderNo);
            mallOrderItem.setProductId(backOrderItemVo.getProductId());
            MallProduct mallProduct = mallProductMapper.selectByProductId(backOrderItemVo.getProductId());
            mallOrderItem.setProductImage(mallProduct.getMainImage());
            mallOrderItem.setQuantity(backOrderItemVo.getWeight());
            String []nameStr = mallProduct.getName().split(",");
            mallOrderItem.setProductModel(nameStr[2]);
            mallOrderItem.setProductName(mallProduct.getName());
            mallOrderItem.setUserId(customerUserId);
            mallOrderItem.setResidualQuantity(backOrderItemVo.getWeight());
            mallOrderItem.setUpdateTime(new Date());
            BigDecimal bWeight = backOrderItemVo.getWeight();

            mallOrderItem.setTotalPrice(backOrderItemVo.getPrice().multiply(bWeight));
//                mallOrderItem.set
            allPrice = allPrice.add(backOrderItemVo.getPrice().multiply(bWeight));
            try {
                mallOrderItemMapper.insert(mallOrderItem);
            } catch (Exception e) {
                return ServerResponse.createByErrorMessage("订单详情创建失败");
            }
        }

        MallOrder mallOrder = new MallOrder();
        mallOrder.setOrderNo(orderNo);
        mallOrder.setUserId(customerUserId);
        mallOrder.setShippingId(shippingId);
        mallOrder.setPayment(allPrice);
        mallOrder.setPaymentType(1);
        mallOrder.setStatus(10);

        mallOrder.setStatus1(0);

        mallOrder.setCreateTime(new Date());
        mallOrder.setUpdateTime(new Date());
        mallOrder.setDistcode(distCode);
        mallOrder.setIsSample(0);
        mallOrder.setSubmitPerson(2);
        mallOrder.setEnabled(1);
        mallOrder.setShopId(1);
        mallOrder.setMessage(opinion);
        mallOrder.setUpdateTime(new Date());
        mallOrder.setTransportId(transportId);
        mallOrder.setDealerId(customerMapper.selectByUserId(customerUserId).getDealerId());
//        SysCustomer sysCustomer = customerMapper.selectByUserId(customerUserId);
//        mallOrder.setDealerId(sysCustomer.getDealerId());
        try {
            mallOrderMapper.myInsert(mallOrder);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("订单创建失败");
        }

        return ServerResponse.createBySuccess("订单创建成功");
    }

    /**
     * @Date 2018/11/8 16:09
     * @Param [orderItemJsonStr, fufillmentNo, address]
     * @return com.hmall.common.ServerResponse
     * @Description // 发货
     */
    public ServerResponse sendOrder(String orderItemJsonStr, String fufillmentNo, String address) throws InterruptedException {

//        String testStr = "[{\"orderItemId\":2081,\"weight\":1}]";
//           orderItemJsonStr = testStr;

        Integer count = mallOrderFufillmentParentMapper.selectByFufillmentNo(fufillmentNo);
        if(count > 0) {
            return ServerResponse.createByErrorMessage("该发货号已存在");
        }

        List<BackSendOrderItemVo> backSendOrderItemVoList = JsonUtils.jsonToList(orderItemJsonStr, BackSendOrderItemVo.class);

        if(0 == backSendOrderItemVoList.size()){
            return ServerResponse.createByErrorMessage("无产品发货");
        }
        MallOrderItem mallOrderItemZero = mallOrderItemMapper.selectByPrimaryKey(backSendOrderItemVoList.get(0).getOrderItemId());
        //订单编号
        Long orderNo = mallOrderItemZero.getOrderNo();

        //订单变成发货中
        mallOrderMapper.updateByOrderNo(60, orderNo);

        //客户编号;
        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(mallOrderItemZero.getUserId());

        //更新父
        MallOrderFufillmentParent mallOrderFufillmentParent = new MallOrderFufillmentParent();
        mallOrderFufillmentParent.setFufillmentNo(fufillmentNo);
        mallOrderFufillmentParent.setOrderNo(orderNo);
        mallOrderFufillmentParent.setCreateTime(new Date());
        mallOrderFufillmentParent.setIsReceived(0);
        mallOrderFufillmentParent.setAddress(address);

        BigDecimal price = new BigDecimal(0);
        //更新子
        for (BackSendOrderItemVo backSendOrderItemVo : backSendOrderItemVoList) {
            MallOrderFufillment mallOrderFufillment = new MallOrderFufillment();
            mallOrderFufillment.setOrderItemId(backSendOrderItemVo.getOrderItemId());
            MallOrderItem mallOrderItem = mallOrderItemMapper.selectByPrimaryKey(backSendOrderItemVo.getOrderItemId());


            mallOrderFufillment.setModel(mallOrderItem.getProductModel());
            BigDecimal weight = backSendOrderItemVo.getWeight();


            price = price.add(weight.multiply(new BigDecimal(mallOrderItem.getCurrentUnitPrice().doubleValue())));
            //更新orderItem里的剩余发货量
            mallOrderItemMapper.updateResidualQuantity(backSendOrderItemVo.getOrderItemId(), weight);
            mallOrderFufillment.setFufillmentNo(fufillmentNo);

            mallOrderFufillment.setWeight(weight);
            mallOrderFufillment.setSendTime(new Date());
            //创建订单 未发货更新

            mallOrderFufillment.setCustomerId(customerId);

            mallOrderFufillmentMapper.insert(mallOrderFufillment);
        }

        //本次发货应付的金额
        mallOrderFufillmentParent.setUnpayment(price);
        mallOrderFufillmentParent.setStatus(0);

        mallOrderFufillmentParentMapper.insert(mallOrderFufillmentParent);

        //订单状态变成50交易完成节点在发货确认完成

        //发货
        //1.更新发货金额
        //2.更新本月欠款金额
        //3.更新unpayment表

        //如果新绑定的公司很可能没有这个表导致错误
        //2018/10/12
        //账期客户发货的时候才加欠款

        SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customerId);

        if(null != sysCustomerCredit) {
           merchandiserService.updateUnPaymentAndStatement(customerId, price);
        }
        commentService.createDefaultComment(orderNo);

        return ServerResponse.createBySuccess("发货成功");
    }

    /**
     * @Date 2018/11/8 16:13
     * @Param [userId, customerUserId]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.BackOrderFilter>>
     * @Description // 获得用户的订单的筛选项以及数目
     */
    public ServerResponse<List<BackOrderFilter>> getOrderFilter(Integer userId, Integer customerUserId) {

        List<BackOrderFilter> backOrderFilterList = new ArrayList<>();


        List<String> menuList = menuMapper.listMenuByUserId(userId);
        int role = DealerMenuUtil.getBackRole(menuList);

        List<Integer> salesmanIdList = new ArrayList<>();
        if (role == 0) {
            //办事员
            salesmanIdList.add(userId);
        } else {
            salesmanIdList = getSalesmanIdList(userMapper.selectByPrimaryKey(userId).getDeptId());
        }

        //一个用户绑定一个业务员，不会重复
        //1.找到所有的业务员绑定的客户
        //2.找到所有客户的订单

        //找到所有业务员绑定的用户
        List<Integer> customerUserIdList = new ArrayList<>();
        if(null == customerUserId) {
            for (Integer salesmanId : salesmanIdList) {
                List<Integer> customerIdList = getCustomerIdList(salesmanId);
                for (Integer customerId : customerIdList) {
                    customerUserIdList.addAll(getCustomerUserIdList(customerId));
                }
            }
        }else{
            customerUserIdList.add(customerUserId);
        }

        Set<Integer> set = new HashSet<>(customerUserIdList);
        customerUserIdList.clear();
        customerUserIdList.addAll(set);

        List<MallOrder> orderList = new ArrayList<>();
        if (customerUserIdList.size() != 0) {
            orderList = mallOrderMapper.selectOrderIdByUserIdList(customerUserIdList);
//            orderList = mallOrderMapper.selectOrderWithDetail(orderList);
        }




        BackOrderFilter b1 = new BackOrderFilter("全部", 0);
        BackOrderFilter b2 = new BackOrderFilter("待审核", 0);
        BackOrderFilter b3 = new BackOrderFilter("待发货", 0);
        BackOrderFilter b4 = new BackOrderFilter("交易完成", 0);
        BackOrderFilter b5 = new BackOrderFilter("已发货", 0);

//        BackOrderFilter b5 = new BackOrderFilter("付款凭证未上传", 0);
//        BackOrderFilter b6 = new BackOrderFilter("付款凭证未审核", 0);
        BackOrderFilter b7 = new BackOrderFilter("已取消", 0);
        BackOrderFilter b8 = new BackOrderFilter("退换货", 0);
        BackOrderFilter b9 = new BackOrderFilter("申诉", 0);
        BackOrderFilter b10 = new BackOrderFilter("差评", 0);
        BackOrderFilter b11 = new BackOrderFilter("拿样", 0);

/*订单状态：审核中-10，审核过待付款(未付定金）-30，已付款待发货-20， 发货中，可以进行评价-60 ，已取消-0，用户收货确认即交易完成-50
付款凭证审核中 70 */
        int all = 0;
        for (MallOrder mallOrder : orderList) {
            //0表示不是拿样
            if (mallOrder.getIsSample() == 0) {
                //有订单状态的
                switch (mallOrder.getStatus()) {
                    case 10: {
                        b2.add();
                        all++;
                        break;
                    }
                    case 20: {
                        b3.add();
                        all++;
                        break;
                    }
                    case 60: {
                        b5.add();
                        all++;
                        break;
                    }
                    case 70: {
                        b3.add();
                        all++;
                        break;
                    }
                    case 50: {
                        b4.add();
                        all++;
                        break;
                    }
                    case 30: {
                        //更新时间
                        b3.add();
                        all++;
                        break;
                    }
                    case 0: {
                        b7.add();
                        all++;
                        break;
                    }
                    default: {
                        break;
                    }
                }
                //申诉 没有入口
                //差评 暂时不做
            } else {
                b11.add();
            }
        }
        b1.setOrderNumber(all);

        b8.setOrderNumber(0);
        b9.setOrderNumber(0);
        b10.setOrderNumber(0);

        backOrderFilterList.add(b1);
        backOrderFilterList.add(b2);
        backOrderFilterList.add(b3);
        backOrderFilterList.add(b4);
        backOrderFilterList.add(b5);
        backOrderFilterList.add(b7);
        backOrderFilterList.add(b8);
        backOrderFilterList.add(b9);
        backOrderFilterList.add(b10);
        backOrderFilterList.add(b11);
        return ServerResponse.createBySuccess(backOrderFilterList);
    }

    /**
     * @Date 2018/11/8 16:24
     * @Param [customerUserId]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.CustomerInformationVo>
     * @Description // 根据用户得到公司信息
     */
    public ServerResponse<CustomerInformationVo> getCustomerInformation(Integer customerUserId) {

        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(customerUserId);
        if (customerId == null) {
            return ServerResponse.createByErrorMessage("该用户没有绑定公司");
        }
        CustomerInformationVo customerInformationVo = new CustomerInformationVo();
        SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customerId);
        if (sysCustomerCredit != null) {
            customerInformationVo.setCustomerType(1);
            customerInformationVo.setAccountPeriod(sysCustomerCredit.getAccountPeriod());
        } else {
            customerInformationVo.setAccountPeriod(0);
            customerInformationVo.setCustomerType(0);
        }

        MallPaymentUnpay mallPaymentUnpay = mallPaymentUnpayMapper.selectByPrimaryKey(customerId);
        //超额 = 总额度 - 欠款
        BigDecimal quota = null == sysCustomerCredit ? new BigDecimal(0) : new BigDecimal(sysCustomerCredit.getQuota());
        BigDecimal unpay = null == mallPaymentUnpay ? new BigDecimal(0) : mallPaymentUnpay.getUnpayPayment();
        customerInformationVo.setExceedUnPayment(unpay.subtract(quota));

        ServerResponse response = getOrderDetailMessage(customerId);
        String message = "";
        if(customerInformationVo.getCustomerType() == 0) {
            if (0 == response.getStatus()) {
                message = response.getData().toString();
            } else {
                message = response.getMsg();
            }
        }
        customerInformationVo.setMessage(message);
        return ServerResponse.createBySuccess(customerInformationVo);
    }

    /**
     * @Date 2018/11/8 15:56
     * @Param [userId, customerId, year]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.AccountHistoryVo>>
     * @Description // 后台人员拿到对账记录
     */
    public ServerResponse<List<AccountHistoryVo>> getStatementOfAcccountHistory(Integer userId, Integer customerId, Integer year) {

        //
        List<String> menuList = menuMapper.listMenuByUserId(userId);
        int role = DealerMenuUtil.getBackRole(menuList);

        //根据不同的权限得到不同的客户列表
        List<Integer> customerIdList = new ArrayList<>();

        if (role == 0) {
            //业务员只能看到自己绑定的公司的信息
            customerIdList = getCustomerIdList(userId);
        } else {
            //管理员可以看到下面所有的业务员的绑定的公司的信息
            List<Integer> salesmanIdList = getSalesmanIdList(userMapper.selectByPrimaryKey(userId).getDeptId());
            for (Integer salesmanId : salesmanIdList) {
                customerIdList.addAll(getCustomerIdList(salesmanId));
            }
        }

        if(null != customerId){
            for(int i = 0; i < customerIdList.size(); i++){
                if(customerId.equals(customerIdList.get(i))){
                    customerIdList.remove(i);
                }
            }
        }


        List<AccountHistoryVo> accountHistoryVoList = new ArrayList<>();
        //根据customerIdList得到月份列表
        if(customerIdList.size() != 0) {
            accountHistoryVoList = userService.getStatementOfAccountHistory(customerIdList, year).getData();
        }
        return ServerResponse.createBySuccess(accountHistoryVoList);
    }

    /**
     * @Date 2018/11/8 15:58
     * @Param [customerId]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.TimeOutSendVo>>
     * @Description // 得到公司超时的发货列表
     */
    public ServerResponse<List<TimeOutSendVo>> getTimeOutSendList(Integer customerId) {

        Calendar calendar = Calendar.getInstance();
        List<MallOrderFufillmentParent> mallOrderFufillmentParentList = mallOrderFufillmentParentMapper.selectTimeOutList(customerId, calendar.getTime());
        List<TimeOutSendVo> timeOutSendVoList = new ArrayList<>();
        for(MallOrderFufillmentParent mallOrderFufillmentParent : mallOrderFufillmentParentList){
            TimeOutSendVo timeOutSendVo = new TimeOutSendVo();
            int accountPeriod = 0;
            SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customerId);
            if(null != sysCustomerCredit){
                accountPeriod = sysCustomerCredit.getAccountPeriod();
            }
            timeOutSendVo.setAccountPeriod(accountPeriod);
            timeOutSendVo.setCustomerName(customerMapper.selectByPrimaryKey(customerId).getBusName());
            timeOutSendVo.setNeedPaymentTime(mallOrderFufillmentParent.getPayTime());
            timeOutSendVo.setSendTime(mallOrderFufillmentParent.getCreateTime());
            timeOutSendVo.setUnpaymentPrice(mallOrderFufillmentParent.getUnpayment());
            timeOutSendVoList.add(timeOutSendVo);
        }
        return ServerResponse.createBySuccess(timeOutSendVoList);
    }


    /**
     * @Date 2018/11/8 16:03
     * @Param [customerId]
     * @return com.hmall.common.ServerResponse
     * @Description // 得到订单详情信息
     */
    public ServerResponse getOrderDetailMessage(Integer customerId) {

        SysCustomer sysCustomer = customerMapper.selectByPrimaryKey(customerId);
        if (sysCustomer == null) {
            return ServerResponse.createByErrorMessage("无该客户");
        }
        SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customerId);
        boolean creditCheck = sysCustomerCredit == null || (sysCustomerCredit.getQuota() == 0 && sysCustomerCredit.getAccountPeriod() == 0);
        if (creditCheck){
            List<MallOrder> list = mallOrderMapper.selectPassOrderByCustomerId(customerId);
            if (list.size() > 0){
                Integer count1 = mallPaymentVoucherMapper.selectUnExamVoucher(customerId);
                if (count1 > 0){
                    return ServerResponse.createBySuccess("该客户当前有未支付订单");
                }else {
                    for (MallOrder aList : list) {
                        Long orderNo = aList.getOrderNo();
                        MallPaymentVoucher mallPaymentVoucher = mallPaymentVoucherMapper.selectByOrderNo(orderNo);
                        if (mallPaymentVoucher == null) {
                            return ServerResponse.createBySuccess("该客户当前有未支付订单");
                        }
                    }
                }
                return ServerResponse.createByErrorMessage("该现金客户一切正常");
            }else {
                return ServerResponse.createByErrorMessage("该客户没有待发货或凭证审核中的订单");
            }
        }else {
            return ServerResponse.createByErrorMessage("该用户为账期客户");
        }

    }

    public ServerResponse<PageVo<MallProductForwardStock>> getProductStockList(String materialCode, Integer pageNum, Integer pageSize) {

        int size = mallProductForwardStockMapper.selectAllCount(materialCode);
        int start = pageSize * (pageNum - 1);
        int end = Math.min(start + pageSize, size);


        List<MallProductForwardStock> mallProductForwardStockList = mallProductForwardStockMapper.selectByLimit(materialCode, start, end);


        PageVo<MallProductForwardStock> pageVo = new PageVo<>(pageNum, pageSize, size, mallProductForwardStockList);

        return ServerResponse.createBySuccess(pageVo);
    }

    public ServerResponse<List<String>> getProductMaterialList(String materialCode) {

        List<String> materialModelList = mallProductForwardStockMapper.selectByMaterialCodeWithLimit(materialCode, 20);

        return ServerResponse.createBySuccess(materialModelList);
    }

    /**
     * @Date 2018/11/8 16:02
     * @Param [userId]
     * @return boolean
     * @Description // 校验是资金用户
     */
    private boolean checkFinance(Integer userId){

        SysUserRole userRole = sysUserRoleMapper.selectRole(userId);
        if(userRole != null){
            return userRole.getRoleId() == 112;
        }
        return false;
    }

    /**
     * @Date 2018/11/8 15:55
     * @Param [model, twisting, grade]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.model.MallProductForwardStock>>
     * @Description // 得到库存信息
     */
    public ServerResponse<List<MallProductForwardStock>> getProductForwardStockInformation(String model, String twisting, String grade, String color) {

        if(twisting.endsWith("捻")){
            twisting = twisting.substring(0, twisting.length() - 1);
        }
        List<MallProductForwardStock> mallProductForwardStockList = mallProductForwardStockMapper.selectStockByLimit(model, twisting, grade, color);

        return ServerResponse.createBySuccess(mallProductForwardStockList);
    }

    public ServerResponse<List<MallProductForwardStockVo>> getBatchProductForwardStockInformation(String productAttrJson) {

        //json转换
//        JSONArray productAttrJsonArray = JSONArray.fromObject(productAttrJson);
        List<MallProductAttrVo> mallProductAttrVoList;
//        for (int i = 0; i < productAttrJsonArray.size(); i++) {
//            MallProductAttrVo mallProductAttrVo = (MallProductAttrVo) JSONObject.toBean((JSONObject) productAttrJsonArray.get(i), MallProductAttrVo.class);
//            mallProductAttrVoList.add(mallProductAttrVo);
//        }
        mallProductAttrVoList = JsonUtils.jsonToList(productAttrJson, MallProductAttrVo.class);

        //传换成vo
        List<MallProductForwardStockVo> mallProductForwardStockVoList = new ArrayList<>();
        for(MallProductAttrVo mallProductAttrVo : mallProductAttrVoList){
            String model = mallProductAttrVo.getModel();
            String grade = mallProductAttrVo.getGrade();
            String twisting = mallProductAttrVo.getTwisting();
            String color = mallProductAttrVo.getColor();
            MallProductForwardStockVo mallProductForwardStockVo = new MallProductForwardStockVo();
            mallProductForwardStockVo.setGrade(grade);
            mallProductForwardStockVo.setTwisting(twisting);
            mallProductForwardStockVo.setModel(model);
            mallProductForwardStockVo.setColor(color);
            mallProductForwardStockVo.setMallProductForwardStockList(getProductForwardStockInformation(model, twisting, grade, color).getData());
            mallProductForwardStockVoList.add(mallProductForwardStockVo);
        }
        return ServerResponse.createBySuccess(mallProductForwardStockVoList);
    }


    /**
     * @Date 2018/11/8 16:24
     * @Param [materialCode, pageNum, pageSize]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo>
     * @Description // 通过物料编码得到产品列表
     */
    public ServerResponse<PageVo<ProductMaterialVo>> getProductListByMaterialCode(String materialCode, Integer pageNum, Integer pageSize) {

        //先根据物料编码去stock表匹配产品

        List<ProductMaterialVo> productMaterialVoList = new ArrayList<>();
        //匹配到具体的物料编码得到Model grade 捻度去product表得到更多信息
        List<MallProductForwardStock> mallProductForwardStockList = mallProductForwardStockMapper.selectByMaterialCode(materialCode);
        for(MallProductForwardStock tMallProductForwardStock : mallProductForwardStockList){
            String model = tMallProductForwardStock.getModel();
            String grade = tMallProductForwardStock.getGrade();
            String twisting = tMallProductForwardStock.getTwisting();
            if("S".equals(twisting) || "Z".equals(twisting)){
                twisting += "捻";
            }
            List<MallProduct> mallProductList = mallProductMapper.selectByModelTwistingAndGrade(model, twisting, grade);
            for(MallProduct mallProduct : mallProductList) {
                if (mallProduct != null) {
                    ProductMaterialVo productMaterialVo = new ProductMaterialVo();
                    productMaterialVo.setImg(mallProduct.getMainImage());
                    productMaterialVo.setName(mallProduct.getName());
                    productMaterialVo.setModel(model);
                    productMaterialVo.setGrade(grade);
                    productMaterialVo.setTwisting(twisting);
             
                    MallProductForwardFormateVo mallProductForwardStock = new MallProductForwardFormateVo(tMallProductForwardStock.getId(), tMallProductForwardStock.getInventoryOrganization(), tMallProductForwardStock.getFactory(), tMallProductForwardStock.getMaterialCode(), tMallProductForwardStock.getMaterialName(),
                            tMallProductForwardStock.getSpecifications(), tMallProductForwardStock.getModel(), tMallProductForwardStock.getGradeInfo(), tMallProductForwardStock.getMachineType(), tMallProductForwardStock.getBuyNumber(), tMallProductForwardStock.getGrade(), tMallProductForwardStock.getTwisting(), tMallProductForwardStock.getStatus(), tMallProductForwardStock.getCanBuyNumber(), tMallProductForwardStock.getBuyNumber(), tMallProductForwardStock.getSendNumber(), tMallProductForwardStock.getWaitOutNumber(), tMallProductForwardStock.getWaitInNumber(), tMallProductForwardStock.getStock(),
                            tMallProductForwardStock.getStockBoxNumber(), tMallProductForwardStock.getSortCode(), tMallProductForwardStock.getSortName());
                    productMaterialVo.setMallProductForwardStock(mallProductForwardStock);
                    productMaterialVo.setProductId(mallProduct.getId());
                    productMaterialVoList.add(productMaterialVo);
                }
            }
        }
        Integer start = (pageNum - 1) * pageSize;
        Integer count = productMaterialVoList.size();
        Integer end = Math.min(count, start + pageSize);
        List<ProductMaterialVo> subProductMaterialVoList = productMaterialVoList.subList(start, end);
        PageVo<ProductMaterialVo> pageVo = new PageVo<>(pageNum, pageSize, count, subProductMaterialVoList);
        return ServerResponse.createBySuccess(pageVo);
    }

    /**
     * @Date 2018/11/13 17:18
     * @Param []
     * @return com.hmall.common.ServerResponse
     * @Description  得到常量列表
     */
    public ServerResponse getConstList() {

        String []dictionKeyList = {"sales_organization", "sales_type", "freight_payment_type", "payment_methods", "rate"};
        OrderDetailConstVo orderDetailConstVo = new OrderDetailConstVo();
        orderDetailConstVo.setSalesOrganizationList(dictionMapper.selectListByDictionKey(dictionKeyList[0]));
        orderDetailConstVo.setSalesTypeList(dictionMapper.selectListByDictionKey(dictionKeyList[1]));
        orderDetailConstVo.setFreightPaymentTypeList(dictionMapper.selectListByDictionKey(dictionKeyList[2]));
        orderDetailConstVo.setPaymentMethodList(dictionMapper.selectListByDictionKey(dictionKeyList[3]));
        orderDetailConstVo.setRateList(dictionMapper.selectListByDictionKey(dictionKeyList[4]));
        return ServerResponse.createBySuccess(orderDetailConstVo);
    }


    public ServerResponse deleteSubOrder(Long orderNo, Long groupNo) {

        MallOrder mallOrder = mallOrderMapper.selectAllByOrderNo(orderNo);
        int deleteStatus = 10;
        if(mallOrder.getStatus() != deleteStatus){
            return ServerResponse.createBySuccess("对于非审核中的订单无法进行子订单删除");
        }


        //删除子订单的时候 需要更新orderItem表里的数据如果某个orderItem下的所有的orderItemDetail都被删除要删除本身
        //未实现
        List<MallOrderItemDetail> mallOrderItemDetailList = mallOrderItemDetailMapper.selectByGroupNo(groupNo);
//        Map<Integer, Integer> map = new HashMap<>();
        for(MallOrderItemDetail mallOrderItemDetail : mallOrderItemDetailList){
            Integer itemId = mallOrderItemDetail.getOrderItemId();
            MallOrderItem mallOrderItem = mallOrderItemMapper.selectByPrimaryKey(itemId);
            //更新quantity, totalPrice, residual_quantity

            BigDecimal checkQuantity = new BigDecimal(0.0);
            if(mallOrderItemDetail.getCheckQuantity() != null){
                checkQuantity = mallOrderItemDetail.getCheckQuantity();
            }
            BigDecimal quantity = mallOrderItem.getQuantity().subtract(checkQuantity);
            BigDecimal residualQuantity = mallOrderItem.getResidualQuantity().subtract(checkQuantity);
            BigDecimal totalPrice = mallOrderItem.getTotalPrice().subtract(mallOrderItemDetail.getTotalPrice());
            BigDecimal unitPrice = new BigDecimal(0.0);
            if(quantity.doubleValue() != 0){
                unitPrice = totalPrice.divide(quantity, 2);
            }

            mallOrderItemMapper.updateBySubOrderDetial(itemId, quantity, residualQuantity, totalPrice, unitPrice);
        }

        mallOrderItemDetailMapper.deleteByGroupNo(groupNo);
        return ServerResponse.createBySuccess("删除子订单成功");
    }

}
